Commit Graph

677 Commits

Author SHA1 Message Date
Remy
2f3ff2f0d3
daml-lf: drop TransactionIdString (#4343)
CHANGELOG_BEGIN
CHANGELOG_END
2020-02-03 14:52:33 +00:00
Remy
06967d80fa
Engine: scenario runner prefixes fresh nodeIds and contractIds with #
CHANGELOG_BEGIN
CHANGELOG_END
2020-02-03 14:43:53 +01:00
Samir Talwar
791fad5309
kvutils: Test that the ledger can be restarted and will resume where it left off. (#4321)
* kvutils: Use `ResourceOwner#use` to simplify tests.

* kvutils: Merge in `RestartSpec` from ledger-on-sql.

CHANGELOG_BEGIN
- [KVUtils] Added a test case to the participant state tests to ensure
  your ledger state is resumable upon restart.
CHANGELOG_END

* ledger-on-posix-filesystem: Extract paths into their own class.

* ledger-on-posix-filesystem: Seed the dispatcher with the correct head.

* kvutils: In participant state tests, be clear about different strings.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-31 16:26:36 +00:00
Samir Talwar
35fb5e6351
sandbox: Break dependency cycles. (#4285)
* sandbox: Move common API and indexer deps into their own packages.

Primarily `com.digitalasset.platform.index.store`.

* sandbox: Move API server deps into the `apiserver` and common packages.

CHANGELOG_BEGIN
CHANGELOG_END

* sandbox: Rename `….platform.index.store` to `….platform.store`.

* sandbox: Split `JdbcIndex` & co. out from `apiserver` into `index`.

Moar packages! And this one is nice and clean; there's only a few
dependencies.

* sandbox: Move `InMemoryPackageStore` into its own `packages` package.

`packages` package. What a tongue twister.

* sandbox: Fix warnings in `TransactionConversion`.

* sandbox: Inline `SandboxContractStore` into `LedgerBackedIndexService`.

* sandbox: Fix warnings in `InMemoryLedger` and `SqlLedger`.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-31 16:09:43 +00:00
Samir Talwar
741057ffff
sandbox: Make sure we exit cleanly if the API server fails to start. (#4327)
Previously we were only cleaning up and exiting if loading the DAML
packages failed. Now we also handle API server errors.

An example of where this might happen is if the ledger ID specified is
different to the existing ledger ID, causing an error.

One day we'll kill the ResetService and all of this will go away. One
day…

CHANGELOG_BEGIN
- [Sandbox] Fix an error that stops the server from exiting cleanly if
  API server initialization fails.
CHANGELOG_END

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-31 14:25:41 +00:00
Samir Talwar
389909486d
kvutils: Use matchers in ParticipantStateIntegrationSpecBase. (#4317)
* kvutils: Use matchers in ParticipantStateIntegrationSpecBase.

CHANGELOG_BEGIN
CHANGELOG_END

* kvutils: In participant state tests, always test record time.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-31 12:08:15 +00:00
Stefano Baghino
fabd6d9f2c
Refactor getTimeModel (#4284)
Avoid unnecessary flatmapping/indentation, prepare default response once

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-30 15:19:43 +00:00
Samir Talwar
eaf17cae73
ledger-on-posix-filesystem: Lock the entire ledger with a file lock. (#4249)
* ledger-on-posix-filesystem: Run `scalafmt`.

* ledger-on-posix-filesystem: Just use file channel locks. Seriously.

* ledger-on-posix-filesystem: Rename `FileSystemLock#run` to `apply`.

* ledger-on-posix-filesystem: Conformance tests now run quickly.

So we can stop constraining the number of concurrent test runs.

* ledger-on-posix-filesystem: Lock the entire ledger with a file lock.

This ensures we can't have two separate ledger servers running against
the same directory.

This is mostly an experiment to better understand how to do this on an
SQL ledger for #4039.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-posix-filesystem: Run `scalafmt`.

* ledger-on-posix-filesystem: Use `Resource#use` in `FileSystemLock`.

* resources: Move `Resource#use` to `ResourceOwner#use`.

Makes more sense for the same object to govern both `acquire()` and
`release()`.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-30 14:35:38 +00:00
Samir Talwar
fb58dc8756
ledger-on-sql: Make sure the ledger picks up where it left off. (#4266)
* resources: Make it easy to use a resource and then release it.

* ledger-on-sql: Move database transaction methods to `Database`.

* ledger-on-sql: Make sure the ledger picks up where it left off.

This means seeding the dispatcher with the correct head, rather than
starting at 1 every time.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-sql: Move `Index` and `StartIndex` to the package object.

They're used everywhere.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-30 10:16:32 +00:00
Stefano Baghino
a1f8aeba88
Clean-up JdbcLedgerDao (#4262)
Removes unused call, fixes access modifiers, removes unnecessary curly braces

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-30 08:58:44 +00:00
Stefano Baghino
abde9d3b8b
Fix contract keys test description (#4277)
Reflects the change happened in 81815838a3

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-30 08:49:50 +00:00
Samir Talwar
e54809cecc
sandbox-perf: Fix broken benchmarks and make sure they stay fixed. (#4265)
The `sandbox-perf` build has been failing for a while with the following
errors:

```
INFO: From Generating benchmark code for //ledger/sandbox-perf:sandbox-perf_codegen:
JMH benchmark generation: JMH Benchmark generator failed
JMH benchmark generation: Benchmark classes should not be final.
   [com.digitalasset.platform.sandbox.perf.LargeTransactionBench]
JMH benchmark generation: The instantiated @State class cannot be abstract.
   [com.digitalasset.platform.sandbox.perf.PerfBenchState]
```

However, these errors are ignored; running the benchmarks runs the
`AcsBench` benchmark and ignores the fact `LargeTransactionBench` and
`SimpleBench` failed to compile.

I've fixed the errors by making sure that classes are not final, and
that `SimpleBench` uses a concrete state class.

This also introduces a cheap patch to the Scala JMH Bazel rules that
makes sure they fail if there are any errors.

I'm not really sure how to patch the Bazel rules properly, but someone
else might have an idea. :-)

CHANGELOG_BEGIN
CHANGELOG_END

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-30 08:25:25 +00:00
Samir Talwar
4d324f6aaf
Run scalafmt on all files and fix the errors. (#4260)
Unfortunately, downgrading `scalafmt` resulted in files that would be
reformatted to invalid code, because lines would be merged but trailing
commas would be left in.

I've manually run it everywhere and fixed these issues so people don't
have to fix them as they go.

CHANGELOG_BEGIN
CHANGELOG_END

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-29 16:15:49 +00:00
Samir Talwar
f9de93b192
ledger-on-sql: Don't allow unnamed in-memory databases. (#4255)
* ledger-on-sql: Don't allow unnamed in-memory databases.

It seems that changing the connection pool size at runtime causes weird
issues, predominantly that sometimes all connections are dropped and
therefore the in-memory database is lost after migration. Obviously, it
then stops working.

This works around this problem by simply not allowing unnamed in-memory
databases, guaranteeing that we can share the database between the
various connection pools.

This will probably be necessary anyway when attempting to share the
database between the ledger and the index.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-sql: Make it clear we're generating a new JDBC URL in tests.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-29 10:34:00 +00:00
Miklos
f6939ccac2
Validate submission inputs vs. outputs (#4242)
Check submission inputs vs. outputs right after processing submission.

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-29 11:14:34 +01:00
Samir Talwar
3ac5b8f9da
ledger-on-whatever: Enable more conformance tests. (#4250)
* ledger-on-{memory,posix-filesystem,sql}: Enable slow conformance tests.

They're now fast enough. :-)

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-{memory,posix-filesystem,sql}: Enable config management tests.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-29 09:30:49 +00:00
Samir Talwar
c81cc2ab2a ledger-on-sql: Migrate tables using Flyway. (#4232)
* ledger-on-sql: Pull out a superclass for the various integration tests.

* ledger-on-sql: Use Flyway to migrate tables in an idempotent manner.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-sql: Make it easy to run it with Bazel for experimentation.

* ledger-on-sql: Test that migrations will never change in the future.

* ledger-on-sql: Add a prefix of "ledger_" to the tables.

This is so we don't accidentally conflict with the index when the
schemas are shared.

I am letting myself modify the migrations because the existing
migrations haven't been merged into `master` yet.

* ledger-on-sql: Explain why we change the pool size after migration.

* ledger-api-test-tool: Tests now specify a timeout scale, not a timeout.

Makes it easier to change the default timeout in one place.

* ledger-api-test-tool: Increase timeouts on slow tests.

These tests produce a lot of volume and can make CI flaky.

* ledger-on-sql: Only tear down PostgreSQL in tests.

For other databases, we just create a new file for each test case.

* ledger-on-sql: Reduce the log output in tests.

* ledger-on-sql: Use a separate connection pool for Flyway when possible.

Apparently `setMaximumPoolSize` doesn't really have the desired effect
after the connection pool has already been used. The new test case will
be flaky if we process more than one commit in parallel.

For SQLite, it seems to be OK.

* ledger-on-sql: Use a separate connection pool for Flyway with SQLite.

Except in memory.

* ledger-on-sql: Use a separate PostgreSQL database for each test.

Because performance, innit. Don't have to tear them down.

* ledger-on-sql: Move the `Queries` values inside the `RDBMS` objects.

* ledger-on-sql: Go into even more detail about pool size hijinks.

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-28 16:16:23 +00:00
Samir Talwar
02b1c8be59 ledger-api-test-tool: Run scalafmt. (#4241)
It affects basically every file, so let's do it all at once.

CHANGELOG_BEGIN
CHANGELOG_END

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-28 13:29:21 +00:00
Samir Talwar
ebfb0c4a97 sandbox: On initialization error, actually print the error and stop. (#4239)
Three problems here:

1. On failure, the Sandbox didn't close down the metrics reporting
thread, meaning the application would hang.
2. If there's a failure:
  a. we didn't print it, and
  b. we didn't exit with the correct status code.

These are now handled.

CHANGELOG_BEGIN
- [Sandbox] On initialization error, report the error correctly and exit
  with a status code of 1. Previously, the program would hang
  indefinitely. (This regression was introduced in v0.13.41.)
CHANGELOG_END

Co-authored-by: Samir Talwar <samir.talwar@digitalasset.com>
2020-01-28 12:25:29 +00:00
Samir Talwar
2737303ac1
sandbox: Upgrade Flyway from v5 to v6. (#4207)
* sandbox: Ensure that the Flyway tests actually pick up the SQL files.

* sandbox: Upgrade Flyway from v5 to v6.

CHANGELOG_BEGIN
- [Sandbox] Upgrade the Flyway database migrations library from v5 to v6.
CHANGELOG_END
2020-01-24 19:36:31 +01:00
Stefano Baghino
243746d465 Add logging context information to ledger services (#4205)
* Add logging context information to ledger services

Rolls back that AllowedType implicit, which made the logging context
less usable and didn't provide that much of an advantage. Replaced with
helpers where it makes sense that take care of turning the value safely
into a string.

Closes #3699

CHANGELOG_BEGIN
CHANGELOG_END

* Remove unused import

* Address https://github.com/digital-asset/daml/pull/4205#discussion_r370704306
2020-01-24 18:28:08 +00:00
Samir Talwar
0be3e72a12
ledger-on-sql: PostgreSQL support. (#4204)
* ledger-on-sql: Don't bother cleaning up after integration tests.

Turns out Bazel cleans up before each test run, so we only have one
set of outputs at a time. This is far more useful for debugging anyway.

* ledger-on-sql: Pull out a test-lib to simplify the conformance tests.

* ledger-on-sql: Turn `Database` from a sealed trait into a case class.

* ledger-on-sql: Support for PostgreSQL!

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-sql: Run the conformance tests against PostgreSQL.

* ledger-on-sql: Run the LotsOfParties conformance tests.

* ledger-on-sql: Use PostgreSQL's `RETURNING` keyword to save a query.

* ledger-on-sql: Ensure the reader connection pool is read-only.

* ledger-on-sql: Avoid cloning ByteStrings as byte arrays where possible.

Instead, use `ByteString#newInput()`, which returns an `InputStream`.
This is supported by H2 and PostgreSQL, but unfortunately not SQLite.

* ledger-on-sql: Run integration tests in parallel.

* Update the PostgreSQL and SQLite JDBC drivers.
2020-01-24 15:33:11 +01:00
Samir Talwar
f3f7def5d2
postgresql-testing: Extract PostgresAround from the Sandbox t… (#4197)
* postgresql-testing: Extract `PostgresAround` from the Sandbox tests.

CHANGELOG_BEGIN
CHANGELOG_END

* postgresql-testing: Split into several files.

* postgresql-testing: Pull out the host and database names into variables.

* postgresql-testing: Don't publish to Maven.

I have no idea why the build wasn't failing before.

* postgresql-testing: Assimilate the `@postgresql_dev_env` dependency.
2020-01-24 12:48:36 +01:00
Samir Talwar
e13f9a7edd
kvutils: Use resources in KeyValueParticipantState, not AutoClo… (#4177)
* kvutils: Use resources in KeyValueParticipantState, not AutoCloseable.

CHANGELOG_BEGIN
- [kvutils] The simplified API now uses ``com.digitalasset.resources``
  to manage acquiring and releasing resources instead of ``Closeable``.
CHANGELOG_END

* ledger-on-posix-filesystem: Remove dead code due to a refactoring fail.
2020-01-23 16:59:01 +01:00
nickchapman-da
62d592ec62
support type synonyms in scala (#4101)
* Support DAML-LF type synonyms in scala.

CHANGELOG_BEGIN
CHANGELOG_END

* dont create synonymns in GenerateSimpleDalf

* extend DAML-LF parser to support type synonyms

* test: expand type synonyms correctly
2020-01-23 10:49:28 +00:00
Stefano Baghino
54abbf34ce
Add parties to logging context of active contracts service (#4175)
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-23 10:47:16 +01:00
Samir Talwar
6c1d931c05
ledger-api-test-tool-on-canton: Upgrade to Canton v0.7.0 and cl… (#4170)
* ledger-api-test-tool-on-canton: Upgrade Canton to v0.7.0.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-api-test-tool-on-canton: Use the health endpoint instead of `nc`.

Netty prints a warning when kicking it with `nc -z` from Nix's
netcat-gnu. Not other netcats though… don't know why.

* ledger-api-test-tool-on-canton: Let IntelliJ format the shell script.

* ledger-api-test-tool-on-canton: Stop Canton with SIGINT.

For some reason, Canton doesn't print out a load of errors if it's
stopped with SIGINT (Ctrl+C). SIGTERM, on the other hand…

* ledger-api-test-tool-on-canton: Write Canton logs to STDOUT.

Now the logs are no longer noisy, we can just pump them to STDOUT. This
should make debugging any transient issues on CI a lot easier.
2020-01-23 09:04:16 +01:00
Remy
b6e848b576
Engine: Add node and contract Discriminator
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-22 18:49:30 +01:00
Samir Talwar
eeaa2edc91
ledger-on-posix-filesystem: Fix the tests on CI. (#4166)
* libs-scala: Make sure `RetryStrategy` works if `attempts.isEmpty`.

* ledger-on-posix-filesystem: Only retry on expected lock errors.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-posix-filesystem: Only create the lock attempt directory once.

Soooo much faster.

* ledger-on-posix-filesystem: Don't run the unit tests on Windows.
2020-01-22 18:02:23 +01:00
Samir Talwar
2e3c6b28bd
ledger-on-sql: Get H2 working in the conformance tests. (#4155)
* kvutils: Make logback.xml a base file, rather than the only option.

* kvutils/app: Simplify logback.base.xml.

Mostly by getting rid of unnecessary appenders.

* ledger-on-sql: Add trace logging for all database work.

* Upgrade H2; there's a few useful bug fixes.

* kvutils/app: Let the user override the server JDBC URL.

* kvutils/app: Provide a way to specify the ledger ID.

* ledger-on-sql: If there are missing entries in the log, fail on read.

This can happen right now because we insert in parallel. Next step: stop
doing that.

* ledger-on-sql: Stop writing in parallel; it causes race conditions.

This unfortunately means we also stop _reading_ in parallel, which is
less fun.

* Revert "ledger-on-sql: Use a sequential log entry ID."

This reverts commit c58265bf43.

* ledger-on-sql: Create tables with columns that are not nullable.

* ledger-on-sql: The H2 conformance tests now work, just slowly.

CHANGELOG_BEGIN
CHANGELOG_END

* ledger-on-sql: Run tests against H2 and SQLite on memory and disk.

* ledger-on-sql: Allow H2 to read from the log in parallel with writes.

* ledger-on-sql: Use UUIDs for entry IDs, not 8 random bytes.

* ledger-on-sql: Make sure to log the correlation ID.

* ledger-on-sql: Do less while holding a database connection.

* ledger-on-sql: Log the connection.

* ledger-on-sql: We don't need to tell H2 not to drop the connection.

The connection pool takes care of that.

* ledger-on-sql: Disable H2 conformance tests on CI; they're too slow.

* ledger-on-sql: Rename `loggingContext` to `logCtx`.

* ledger-on-sql: Don't abuse log contexts; put the data in the message.

* ledger-on-sql: Make the connection log line easier to read.

And pull out the logger, even if it's only used once.

* ledger-on-sql: Run the unit tests against (H2, SQLite) * (memory, file).
2020-01-22 16:54:51 +01:00
Remy
63d6e73f4c Engine: Simplify ordering of nodes in transaction (#4140)
* engine: the natural order in Transaction is pre-order traversal

- Do not use anymore SortedMap for nodes in transaction
- Drop unused transaction traversal

CHANGELOG_BEGIN
CHANGELOG_END

* daml-lg: improve generator of transactions
2020-01-22 15:53:44 +00:00
Robert Autenrieth
3f95c2ec13
Change sandbox JWT format (#4070)
* Introduce new JWT payload format
... the reader still supports old formats

CHANGELOG_BEGIN
[Sandbox] The sandbox uses a new payload format for authentication tokens (JWTs).
          The old format is deprecated, but still works.
[JSON API] The HTTP JSON API now uses the same payload format for authentication tokens as the sandbox.
           The old format is deprecated, but still works.
CHANGELOG_END

* Add helper function for getting token party

* Support sandbox tokens in JSON API

* Add warning for deprecated formats

* Update documentation

* Add explicit test for new format

* Update JSON API documentation

* Fix test
2020-01-22 14:26:57 +01:00
Remy
4cc14275d5 engine: node are ordered in transactions (#4129)
* engine: node in children are ordered

CHANGELOG_BEGIN
CHANGELOG_END

* address Gerolf's comment
2020-01-21 14:39:35 +00:00
Samir Talwar
e2a5b26475
contextualized-logging: Move to its own Bazel package. (#4138)
I want to use this in _ledger/ledger-on-sql_, which doesn't depend
directly on Sandbox.

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-21 14:25:06 +01:00
Stefano Baghino
4c5284459c
Standardize metrics naming to snake_case (#4121)
CHANGELOG_BEGIN
[Sandbox] Metrics are now namespaced by "daml" and their names have been
standardize to snake_case
CHANGELOG_END

Please note that HikariJDBC records its own metrics but this is outside
of our reach, so connection-pool-related metrics will keep being called
with camelCase names.
2020-01-21 10:57:38 +01:00
Stefano Baghino
1ad7d6c24c
Replace NamedLoggerFactory (#4097)
* Replace NamedLoggerFactory

CHANGELOG_BEGIN
CHANGELOG_END

* Recover change lost in rebase

* Address https://github.com/digital-asset/daml/pull/4045#discussion_r366883577

* Address https://github.com/digital-asset/daml/pull/4045#discussion_r366885112

* Address two open review comments

Address https://github.com/digital-asset/daml/pull/4045#discussion_r366885448
Address https://github.com/digital-asset/daml/pull/4045#discussion_r366885981

* Address outstanding compilation errors

* Replace mocking with in-memory log collector

* Address https://github.com/digital-asset/daml/pull/4097#pullrequestreview-344639319

* Address https://github.com/digital-asset/daml/pull/4045#discussion_r366886250

The generation of code to have logging in the services has been replaced
by helpers classes. This will allow to enrich the context received at
construction by the service implementations.

* Use ContextualizedLogger for TrackerMap

* Remove deleted logging packages from artifacts.yaml

* Remove remaining deleted artifact from artifacts.yaml

* Address https://github.com/digital-asset/daml/pull/4097#discussion_r368640231

* Address https://github.com/digital-asset/daml/pull/4097#discussion_r368648027

* Address https://github.com/digital-asset/daml/pull/4097#discussion_r368652178

* Address https://github.com/digital-asset/daml/pull/4097#discussion_r368654996

* Annotate type of references to logErrorOnCall

* Address https://github.com/digital-asset/daml/pull/4097#discussion_r368869575
2020-01-21 10:57:28 +01:00
Ognjen Maric
589f710313
Prohibit contract IDs in contract keys and add key maintainers to exercises (#4048)
Prohibit contract IDs in contract keys and add key maintainers to exercises

CHANGELOG_BEGIN

- [DAML-LF] Prohibit contract IDs in contract keys completely. Previously, creating keys containing absolute (but not relative) contract IDs was allowed, but `lookupByKey` on such a key would crash. 

CHANGELOG_END

Co-authored-by: Remy <remy.haemmerle@daml.com>
Co-authored-by: Stephen Compall <scompall@nocandysw.com>
2020-01-20 16:36:38 +01:00
Moritz Kiefer
f77e326e0b Generate stable DA.Time.Types module as DAML-LF 1.6 (#4095)
This was accidentally set to 1.7 before for no reason. Note that this
simply meant that we did not use the stable module when compiling with
--target=1.6 since we filter out newer stable packages.

Nevertheless, I’ve also added a test that verifies that we do not
accidentally introduce dependencies on packages in newer LF versions.

changelog_begin
changelog_end
2020-01-17 18:05:39 +00:00
Samir Talwar
4f12e9be9e Make sure the RecoveringIndexer terminates. (#4034)
* sandbox: Tidy up the RecoveringIndexerSpec a little.

* sandbox: Move the JdbcLedgerDao owner constructor to its object.

* sandbox/damlonx: Make sure the RecoveringIndexer terminates.

Previously, if there was a failure and a termination at the same time,
we could recover after terminating, which means we'd end up in a weird
state. This makes sure we stop correctly.

Unfortunately, I couldn't find a good place to put these tests apart
from in reference-v2, as they need to depend on both _kvutils_ and
_sandbox_. Perhaps they belong in their own Bazel package.

This might address #3945; it's hard to say.

CHANGELOG_BEGIN
- [Indexer] Potentially fix a bug when recovering from failure.
CHANGELOG_END

* reference-v2: Address a race condition in the IndexerIT assertions.

* sandbox: Make sure the RecoveringIndexer can stop during a restart.

* reference-v2: Use Mockito to simulate errors in IndexerIT.

* sandbox: When the RecoveringIndexer is stopped, stop quickly.

* reference-v2: Make sure each test has its own metrics registry.

* Replace TestNamedLoggerFactory with in-memory appender

* sandbox: Test RecoveringIndexerSpec with a mock logger.

Using a real logger was causing massive stack traces in all other tests
that didn't have `RecoveringIndexerSpec$Appender` available, and adding
the appender programmatically didn't work for some reason.

The mock gives much nicer error messages on failure, too.

Co-authored-by: Stefano Baghino <43749967+stefanobaghino-da@users.noreply.github.com>
2020-01-17 14:54:05 +00:00
Stefano Baghino
522555fb69
Replace TestNamedLoggerFactory with in-memory appender (#4071)
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-16 17:07:31 +01:00
Samir Talwar
b96e54f640 libs-scala/resources: Move Resource and friends to their own package. (#4066)
* libs-scala/resources: Move `Resource` and friends to their own package.

CHANGELOG_BEGIN
- [Ledger API Server] Publish the resource management code as a library
  under ``com.digitalasset:resources``.
CHANGELOG_END

* libs-scala/resources: Add to the artifacts list.

* libs-scala/resources: Factor out the test helpers into test/lib.

* libs-scala/resources-akka: Make the Akka resources an optional dep.
2020-01-16 14:13:18 +00:00
Brian Healey
a5490658ac
EC256 rather than EC512 algo (#4019)
* EC256 rather than EC512 algo
CHANGELOG_BEGIN
[Ledger API Authorization]Support EC256 algorithm for JWT rather than EC512
CHANGELOG_END

* support both 256 and 512 ECDSA algo

Signed-off-by: Brian Healey <brian.healey@digitalasset.com>

* scalafmt

* correct comment, avoid unnecessary private def

Signed-off-by: Brian Healey <brian.healey@digitalasset.com>

* correct BAZEL formatter
2020-01-16 08:55:55 -05:00
Stefano Baghino
5231bab423
Introduce ContextualizedLogger and LoggingContext (#4046)
* Introduce ContextualizedLogger and LoggingContext

A ContextualizedLogger is a wrapper around an Slf4j logger. It uses
call-by-name parameters to only construct logging lines when necessary.
The underlying context can be used by invoking withoutContext.

More interestingly, every call to one of its logging methods requires
the presence of an implicit LoggingContext.

A LoggingContext is a way of definining a set of pairs that a
ContextualizedLogger can log without the need of it being specified for
every call.

A new context can be created with newLoggingContext and, given an
implicit LoggingContext, pairs can be added or overwritten using
withEnrichedLoggingContext.

Pairs in the context will be appended to each event logged by a
ContextualizedLogger in the following form:

some text logged explicitly (context: {key1=value1, key2=value2)

If the underlying Logger is configured to use the Logstash encoder the
keys and values in the LoggingContext will also be added to the logging
event encoded in JSON format.

CHANGELOG_BEGIN
CHANGELOG_END

* Apply suggestion in https://github.com/digital-asset/daml/pull/4046#pullrequestreview-343224692

Thanks to @SamirTalwar

Co-Authored-By: Samir Talwar <samir.talwar@digitalasset.com>

* Address https://github.com/digital-asset/daml/pull/4046#discussion_r366874330

Co-authored-by: Samir Talwar <samir@noodlesandwich.com>
2020-01-16 13:05:40 +01:00
Samir Talwar
cb3392fa54 A simplified KVUtils ledger, implemented on SQL with JDBC. (#3940)
* ledger-on-sql: Implement a ledger using the simplified kvutils on JDBC.

This tests against H2; PostgreSQL coming soon.

No changelog because we're not shipping this yet.

CHANGELOG_BEGIN
CHANGELOG_END

* kvutils/app: Extract ledger construction into a trait.

* ledger-on-sql: Run the conformance tests against H2.

* ledger-on-sql: Use H2-specific queries to perform actions atomically.

* ledger-on-sql: Extract queries to `Queries` and `H2Queries`.

* ledger-on-sql: SQLite can't have more than one connection at a time.

* ledger-on-sql: Run conformance tests against SQLite.

* ledger-on-sql: Fix error message if the JDBC URL is missing.

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* kvutils/app: Rename LedgerConstructor to LedgerFactory.

* ledger-on-sql: Don't release connections early.

* ledger-on-sql: Rename `withConnection` so it's more meaningful.

* ledger-on-sql: Use a sequential log entry ID.

* ledger-on-sql: Disable H2 conformance tests.

Until we can figure out why some fail.

Co-authored-by: Gerolf Seitz <gerolf.seitz@digitalasset.com>
2020-01-16 12:02:16 +00:00
Gerolf Seitz
eafeca34a8
Fix bug that can cause the transaction stream to not terminate. (#4053)
Fixes #3984.

CHANGELOG_BEGIN
[Sandbox] Fix bug that can cause the transaction stream to not terminate.
  See `issue #3984 <https://github.com/digital-asset/daml/issues/3984>`__.
CHANGELOG_END

The bug is that the ledger end gets updated without writing any ledger entries,
for example when uploading packages or in case of duplicate commands.

The termination of the stream (i.e. the comparison of offsets) only happened
on actual ledger entries. If there are none, then the stream just waits for the next
entry to be written.

This change moves the stream termination/completion to BEFORE potential entries
are loaded. The stream knows that after a certain offset has been reached, that it can
be terminated/completed.
2020-01-15 15:11:15 +01:00
Samir Talwar
536d6a3f94 A simplified KVUtils ledger, implemented on a POSIX filesystem. (#3933)
* kvutils, etc: Remove duplicate copyright notices.

* ledger-on-posix-filesystem: Implement a simplified KV ledger on FS.

CHANGELOG_BEGIN

- A simple KVUtils-based ledger that runs against a POSIX filesystem.
  Intended as a reference implementation for testing and documentation.

CHANGELOG_END

* ledger-on-posix-filesystem: Make it runnable.

* ledger-on-posix-filesystem: Chunk long state paths for macOS.

macOS only supports file names of up to 255 characters.

* ledger-on-posix-filesystem: Run conformance tests.

The lock is temporarily implemented as an in-memory mutex.

* ledger-on-posix-filesystem: Move the paths into the class.

* ledger-on-posix-filesystem: Lock using the file system.

We use the movement of a directory as an atomic operation.

* ledger-on-posix-filesystem: Use a sequential log entry ID.

* ledger-on-posix-filesystem: Check exception types using patterns.

* ledger-on-posix-filesystem: Test that state key collisions can't happen.

* ledger-on-posix-filesystem: Document the various directories.

* ledger-on-posix-filesystem: Use a *persistent* sequential log entry ID.

Because this is a persistent store. Duh.

* ledger-on-posix-filesystem: Don't worry about using Futures.

It's a global lock anyway.
2020-01-15 14:08:18 +00:00
Stefano Baghino
89f0deda7d
Fix command client integration test flakiness (#4050)
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-15 10:19:19 +01:00
Stefano Baghino
f5b0cf90a4 Drop unused PollingUtils (#4044)
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-14 16:52:32 +00:00
Robert Autenrieth
81815838a3
Check lookup by key nodes (#3834)
* Factor out common values

* Validate LookupByKey nodes

Fixes #3543

CHANGELOG_BEGIN
- [Sandbox] Validate LookupByKey transaction nodes.
  See `issue #3543 <https://github.com/digital-asset/daml/issues/3543>`_.
CHANGELOG_END

* Add failing tests

* LookupByKey validation should not respect privacy

* lookupByKey should use stakeholders, not divulgees

Fixes #2311

CHANGELOG_BEGIN
- [Ledger API] lookupByKey now requires the submitter to be a stakeholder on the referenced contract.
  See `issue #2311 <https://github.com/digital-asset/daml/issues/2311>`_.
CHANGELOG_END

* Adapt tests to new behavior
2020-01-14 14:07:24 +01:00
Martin Huschenbett
099d653373
Allow submitMustFail in scenarios when initializing sandbox (#4036)
Our users seem to stumble over this problem over and over again. Since there's
no technical reason to ban `submitMustFail` during sandbix initialization, we
can also allow for it.

CHANGELOG_BEGIN

- [Sandbox] Allow ``submitMustFail`` in scenarios used for sandbox initialization.

CHANGELOG_END
2020-01-14 12:47:49 +01:00
Miklos
c88d418acc
Sequential log entry ID for InMemoryLedgerReaderWriter (#4012)
CHANGELOG_BEGIN
CHANGELOG_END
2020-01-13 16:35:26 +01:00
Samir Talwar
6bc00da1e2 kvutils: Add a Runner for the simplified KVUtils API. (#3930)
* Initial version of simplified transaction reader/writer API.

* Code tidying.

* Ran ./fmt.sh

* Added verification of pre-declared vs. actual state updates to example.

* kvutils: Run `scalafmt`.

* kvutils: Move ParticipantStateIntegrationSpecBase to src/test/lib.

* kvutils: Clean up warnings in ParticipantStateIntegrationSpecBase.

* ledger-on-memory: Move InMemoryLedgerReaderWriter to its own package.

* ledger-on-memory: Add a Main class with a simple configuration.

* reference-v2/ledger-on-memory: Wait for DARs to upload.

* ledger-on-memory: Run conformance tests.

* kvutils/app: Extract the in-memory ledger `Main` class into a Runner.

* reference-v2: Move InMemoryKVParticipantState out of kvutils.

It's not used elsewhere.

* kvutils/app: Fix some of the config help text.

* kvutils/app: Don't register the archive files twice.

CHANGELOG_BEGIN

- [kvutils/app] A simple way to run KVUtils-based participants.
- [ledger-in-memory] Split out the simple in-memory ledger, previously
  part of kvutils, into its own JAR.

CHANGELOG_END

* Revert "kvutils/app: Don't register the archive files twice."

This reverts commit 2489ae6964.

Turns out we need this for preloading, which is a useful optimization.

Co-authored-by: Miklos <57664299+miklos-da@users.noreply.github.com>
2020-01-13 09:51:07 +00:00
Miklos
1124931f78
Simplified participant-side reader/writer APIs (#3923)
Initial version of simplified participant-side reader/writer APIs.
2020-01-10 12:20:32 +01:00
Gerolf Seitz
779913f8d5
Fix Sandbox CLI help text for the -a option (#4000)
CHANGELOG_BEGIN
[Sandbox] Fix the Sandbox command line help text to reflect the recent
  change that the default address is ``localhost`` (``127.0.0.1`` or
  ``::1``)
CHANGELOG_END
2020-01-10 10:54:09 +01:00
Stefano Baghino
12d7ad809b Move all Api...Service classes to Sandbox package (#3995)
This is done to restrict the usage of NamedLoggerFactory and most usages of MetricsRegistry
to a single Bazel package, thus allowing a possible replacement to not have to become a
dependency of multiple packages.

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-09 14:28:09 +00:00
Brian Healey
95fbf5c921
ECDA512 algorithm support (#3953)
* ECDA512 algorithm support

* ECDA512

* happy day test for ECDA512 algorithm

* failure test for wrong key for ECDA512 algorithm

* add ability to use EC cert file

* update docs

* scalafmt

* Correct documentation

CHANGELOG_BEGIN
[Ledger API Authorization] Support elliptic curve algorithm for JWT verification
CHANGELOG_END

Signed-off-by: Brian Healey <brian.healey@digitalasset.com>

* correct docs warning
2020-01-09 07:25:04 -05:00
David Padbury
3575319005
db: loosen transaction persistence check (#3970)
Currently there is a constraint on the postgres `ledger_entries` table
ensuring that submitter, application_id and command_id are set on
transactions being persisted. These fields are coming from the submitter
info that will be empty when the transaction accepted event is received
on a participant which is not hosting the submitter.

This change updates the check to ensure that all of these fields are
set OR none of them are.

The same change has been made to the H2 migrations with the addition of
correcting the `is not null` check (was previously using `!= null`).

For postgres, as the check is just loosening the existing constraint of all fields
requiring a value I think there is no risk that the new constraint will fail
to apply to existing data. For H2 as the original constraint was
incorrect there is a possibility that existing data may be incorrect -
however as the same component is responsible for writing to H2 and postgres
I will assume the data was correctly persisted regardless of the constraint.
Plus as H2 is typically only used for ephemeral tests, there is
likely no existing data to migrate.

CHANGELOG_BEGIN

- [Sandbox] Loosens database schema to allow persistence of transaction
  ledger entries where no submitter info is present (typically when the
  submitter is hosted by another participant node).

CHANGELOG_END
2020-01-08 12:16:04 -06:00
Jussi Mäki
b8891891a8 Allow omitting submitter info in kvutils transaction log entries (#3966)
* Do not assume submitter info is present in the message

* Make kvutils conversion utilities public

Required for implementing extensions on top of kvutils.

* Make kvutils.Conversions private to com.daml.ledger.participant.state

* Add test case for allowing optional submitter info

* Add changelog markers

CHANGELOG_BEGIN
CHANGELOG_END
2020-01-08 14:21:33 +00:00
Moritz Kiefer
a8b4a84b08
Move most of the remaining serializable types to stable LF packages (#3964)
* Move most of the remaining serializable types to stable LF packages

The only serializable types left in DAML stdlib after this PR are the
following:

- DA.Upgrade:MetaEquiv
- DA.Random:Minstd
- DA.Next.Set:Set
- DA.Next.Map:Map
- DA.Generics:MetaSel0
- DA.Generics:MetaData0
- DA.Generics:DecidedStrictness
- DA.Generics:SourceStrictness
- DA.Generics:SourceUnpackedness
- DA.Generics:Associativity
- DA.Generics:Infix0
- DA.Generics:Fixity
- DA.Generics:K1
- DA.Generics:Par1
- DA.Generics:U1
- DA.Internal.Prelude:Optional

Ignoring the Generics stuff which isn’t very urgent imho and the
Upgrade stuff which is probably going to change significantly anyway,
this leaves us with the weird Random module, the wrappers around
TextMap which will go away anyway and DA.Internal.Prelude:Optional
which shouldn’t exist in the first place (I’ll address that in a
separate PR).

CHANGELOG_BEGIN

- [DAML Compiler] Move more types from daml-stdlib to standalone LF
packages. The module names for the types have also changed
slightly. This only matters over the Ledger API when you specify the
module name explicitly. In DAML you should continue to use the
existing module names.

  - The types from ``DA.Semigroup` are now in a separate package under
  ``DA.Semigroup.Types``
  - The types from ``DA.Monoid` are now in a separate package under
  ``DA.Monoid.Types``
  - The types from ``DA.Time` are now in a separate package under
  ``DA.Time.Types``
  - The types from ``DA.Validation` are now in a separate package
  under ``DA.Validation.Types``
  - The types from ``DA.Logic` are now in a separate package under
  ``DA.Logic.Types``
  - The types from `DA.Date` are now in a separate package under
  `DA.Date.Types`.
  - The `Down` type from `DA.Internal.Prelude` is now in a separate
  package under `DA.Internal.Down`.

CHANGELOG_end

* Fix serializability of RelTime

* fix daml-docs

* Fix tests
2020-01-07 18:25:23 +01:00
Samir Talwar
bbf3fc679d ledger-api-health: Move the values to the companion object. (#3929)
These need to be accessible as `HealthStatus.(un)?healthy` in Java. I
accidentally made them instance methods, which makes life inconvenient.
2020-01-07 11:31:53 +01:00
daravep
b49733b64f Expose address config option in StandloneApiServer (#3906)
* Expose address config option in StandaloneApiServer

Before this PR, it was not possible to set the ledger-api-server
address and so it defaulted to localhost. Now, there is a configuration
variable address in the ApiServerConfig.

* Bind to the loopback address by default instead of the public interface.

CHANGELOG_BEGIN

- [daml-on-x-server] Made ledger api server to bind to localhost by
  default instead to the public interface for security reasons.

CHANGELOG_END
2020-01-07 10:30:31 +01:00
Andreas Herrmann
f33e79c787
Remove unused dependencies to da_scala_library (#3938)
* Inline all scala_library dependencies

* Run //:buildifier-fix

* TMP scala_library_suite --> scala_library

* da_scala_library: Enable unused dependency checker

* scala_library: Enable unused dependency checker

* //daml-lf/data:data

* //daml-lf/engine:engine

* //ledger-api/rs-grpc-akka:rs-grpc-akka

* //ledger/participant-state:participant-state

* //ledger/ledger-api-client:ledger-api-client

* //scala-protoc-plugins/scala-logging:scala-logging-lib

* //ledger/ledger-api-scala-logging:ledger-api-scala-logging

* //ledger/ledger-api-common:ledger-api-common

* //ledger-service/utils:utils

* //ledger-service/jwt:jwt

* //ledger/ledger-api-auth:ledger-api-auth

* //extractor:extractor

* //daml-assistant/scala-daml-project-config:scala-daml-project-config

* //language-support/codegen-common:codegen-common

* //language-support/scala/codegen:codegen

* //language-support/codegen-main:codegen-main-lib

* //ledger-service/db-backend:db-backend

* //ledger-service/http-json:http-json

* //daml-lf/scenario-interpreter:scenario-interpreter

* //ledger/sandbox:sandbox

* //navigator/backend:navigator-library

* //daml-assistant/daml-sdk:sdk-lib

* //daml-lf/data-scalacheck:data-scalacheck

* //daml-script/test:test-lib

* //ledger/ledger-api-common:ledger-api-common-scala-tests-lib

* //ledger/test-common:test-common

* //ledger/sandbox:sandbox-scala-tests-lib

* //extractor:extractor-scala-tests-lib

* //language-support/java/bindings:bindings-java-tests-lib

* //language-support/java/bindings-rxjava:bindings-java-tests-lib

* //language-support/scala/bindings-akka-testing:bindings-akka-testing

* //language-support/scala/codegen-testing:codegen-testing

* //language-support/scala/codegen-sample-app:daml-lf-codegen-sample-app

* //language-support/scala/codegen-sample-app:daml-lf-codegen-sample-app-testing

* //language-support/scala/codegen-testing:codegen-testing-testing

* //ledger-api/sample-service:sample-service

* //ledger-api/rs-grpc-akka:rs-grpc-akka-tests-lib

* //ledger/ledger-api-test-tool:ledger-api-test-tool-lib

* //ledger/ledger-api-test-tool:ledger-api-test-tool-tests

* //ledger/participant-state/kvutils:kvutils

* //ledger/sandbox:ledger-api-server

* //ledger/sandbox-perf:sandbox-perf-lib

* //navigator/backend:navigator-tests-library

* UNDO scala_library_suite --> scala_library

This reverts commit ab3eb1ae23139e2ec431ab4551fbb0371e0354e1.

Co-authored-by: Andreas Herrmann <andreash87@gmx.ch>
2020-01-06 18:14:21 +01:00
Remy
4e5b967a96
SQL Sanbox: Bit more tests for KeyHasher (#3864)
add a bit more tests in order to  test KeyHasher stability
2020-01-06 15:37:00 +01:00
Andreas Herrmann
43bbfeaee6
Remove unused dependencies to da_scala_binary (#3937)
* Inline all scala_binary dependencies

* Run //:buildifier-fix

* da_scala_binary: Enable unused dependency checker

* //compiler/scenario-service/server:scenario-service-raw

* //language-support/scala/codegen:codegen-main

* //daml-lf/encoder:encoder_binary

* //daml-lf/repl:repl

* //language-support/codegen-main:codegen-main

* //language-support/scala/examples:quickstart-scala-bin

* //ledger-api/rs-grpc-akka:rs-grpc-akka-perf

* //ledger-service/jwt:jwt-bin

* //ledger/api-server-damlonx/reference-v2:reference-v2

* //ledger/api-server-damlonx/reference-v2:ephemeral-postgres-reference-server

* //ledger/ledger-api-auth:ledger-api-auth-bin

* //ledger/ledger-api-test-tool:ledger-api-test-tool

* //ledger/participant-state/kvutils/tools:integrity-check

* //navigator/integration-test:navigatortest-jar

* Run //:buildifier-fix

Co-authored-by: Andreas Herrmann <andreash87@gmx.ch>
2020-01-06 13:58:56 +01:00
Andreas Herrmann
6e25d10fe2
daml test-script (#3918)
* Start on daml test-scripts

* Run all `Script a` as test cases

* LedgerClient: Expose PackageManagementClient

To enable DAR uploads

* Upload the DAR to the ledger

* Start sandbox if no ledger specified

* Format daml test-script

* Fix deprecation warning on ActorMaterializer

* Add test-case //daml-script/tests:test_daml_script_test_runner

* Add daml test-script command

CHANGELOG_BEGIN

- [DAML Script - Experimental] Allow running DAML scripts as test-cases.
  Executing ``daml test-script --dar mydar.dar`` will execute all
  definitions matching the type ``Script a`` as test-cases.
  See `#3687 <https://github.com/digital-asset/daml/issues/3687>`__.

CHANGELOG_END

* daml-test-script enable logging

* Remove outdated TODO comment

* daml script-test More elaborate test-caseo

Compare to expected output and add failing test-case

* daml test-script Don't abort on test-failure

Before the test runner would abort on the first failed test-case. This
occasionally introduce additional test-failures if the sandbox was
torn down half-way through execution.

* ./fmt.sh

Co-authored-by: Andreas Herrmann <andreash87@gmx.ch>
2020-01-03 15:01:36 +01:00
Gary Verhaegen
878429e3bf
update copyright notices to 2020 (#3939)
copyright update 2020

* update template
* run script: `dade-copyright-headers update .`
* update script
* manual adjustments
* exclude frozen proto files from further header checks (by adding NO_AUTO_COPYRIGHT files)
2020-01-02 21:21:13 +01:00
Andreas Herrmann
9fbb787062 Remove unused dependencies to da_scala_test(_suite) (#3925)
* Remove unused scala.bzl imports

* override_targets org.scalatest.scalatest_2.12

Otherwise, rules_scala implicitly adds a different version to scala_test
than other packages transitively depending on scalatest. This causes
unused dependency checker to raise an error.

* Handle rules_scala scalatest in pom_file.bzl

* Inline all scala_test dependencies

So that `unused_dependency_checker = "error"` can be applied to them.

* Run //:buildifier-fix

* TMP scala_test_suite --> scala_test

* da_scala_test: Enable unused dependency checker

* //navigator/backend:navigator-scala-tests

* //ledger/sandbox:sandbox-scala-tests

* //ledger/participant-state/kvutils:kvutils-tests

* //ledger/participant-state:participant-state-tests

* //ledger/ledger-api-scala-logging:ledger-api-scala-logging-test

* //ledger/ledger-api-common:ledger-api-common-scala-tests

* //ledger/ledger-api-client:ledger-api-client-tests

* //ledger/ledger-api-auth:ledger-api-auth-scala-tests

* //ledger-service/lf-value-json:tests

* //ledger-service/jwt:tests

* //ledger-service/http-json:tests

* //ledger-api/rs-grpc-akka:rs-grpc-akka-tests

* //language-support/scala/codegen-sample-app:tests

* //language-support/scala/codegen-sample-app:ScalaCodeGenIT

* //language-support/scala/codegen:tests

* //language-support/scala/bindings-akka:tests

* //language-support/java/codegen:test

* //language-support/java/codegen:ledger-tests

* //language-support/java/bindings-rxjava:bindings-java-tests

* //language-support/codegen-common:test

* //extractor:extractor-scala-tests

* //daml-lf/scenario-interpreter:scenario-interpreter_tests

* //daml-lf/language:language-test

* //daml-lf/interface:tests

* //daml-lf/engine:tests

* //daml-lf/encoder:tests

* //daml-lf/archive:daml_lf_archive_reader_tests

* //daml-assistant/scala-daml-project-config:scala-daml-project-config-tests

* UNDO scala_test_suite --> scala_test

This reverts commit 13ed47ba725e944533ca1157a070cb8dc30569ac.

Co-authored-by: Andreas Herrmann <andreash87@gmx.ch>
2019-12-30 13:49:59 +00:00
Samir Talwar
1794d8a2fd Sandbox: Manage resources and close them properly on failure. (#3871)
* sandbox: Create a monadic `ResourceOwner` to manage resources.

* sandbox: Rewrite `ResourceOwner` to be async.

* sandbox: Make sure failed resources are closed immediately.

* sandbox: Better naming in `Open`.

* sandbox: Rename `Open` to `Resource`, and open/close to acquire/release.

* sandbox: Convert `() => AutoCloseable` into `ResourceOwner`.

* sandbox: Refactor the LedgerApiServer in terms of resources.

* sandbox: Explicitly convert `() => AutoCloseable` to `ResourceOwner`.

Explicit > Implicit, right?

* sandbox: Create helpers for converting things to ResourceOwners.

Because I tried to start using them and there was so much code being
written at once.

* sandbox: Simplify construction of JdbcLedgerDao.

* sandbox: Releasing resources should be idempotent.

In that we should only do it once.

* sandbox: Fix the ResetService by closing the API services _first_.

They need to be shut down before the gRPC server.

* sandbox: Don't try and shut down PostgreSQL twice in tests.

* sandbox: Actually run the assertions in ResourceOwnerSpec.

Facepalm.

* sandbox: Test `Resource.sequence` more rigorously.

* sandbox: Move the helpers around `Resource` into `Resource.apply`.

* sandbox: Convert LedgerApiServer resource owners to classes.

* sandbox: Make `ResourceOwner` a monad too, delegating to `Resource`.

* sandbox: Turn `LedgerApiServer` into a ResourceOwner.

* sandbox: Simplify the public signature of `Resource.apply`.

* sandbox: Use ResourceOwners to simplify DB resource management.

This is one hell of a change. Sorry.

* sandbox: Try not to nest `Await.result` calls.

Causes issues when running in a `DirectExecutionContext`.

* sandbox: Turn index subscriptions into resources.

* sandbox: Fix warnings in RecoveringIndexerSpec.

* sandbox: Always release before recovering the indexer.

* sandbox: Add `flatten` and `transformWith` to `Resource`.

* sandbox: If releasing twice in parallel, the second should wait.

* sandbox: If the indexer recovers, clean up the old subscription.

* sandbox: Convert StandaloneIndexerServer into a resource owner.

* sandbox: Convert StandaloneApiServer into a resource owner.

* reference-v2: Rewrite ReferenceServer in terms of resources.

CHANGELOG_BEGIN

- [Reference v2] On an exception, shut down everything and crash.
  Previously, the server would stay in a half-running state.

CHANGELOG_END

* sandbox: Rewrite SandboxServer in terms of resources.

* sandbox: Write the port file in a Future.

* sandbox: JdbcIndexer no longer needs to manage the actorSystem.

* sandbox: Shut down the LedgerApiServer when closing the Sandbox.

* sandbox: Rename `Resource.pure` to `Resource.successful`.

* sandbox: Rename `Resource.sequence_` to `sequenceIgnoringValues`.

* sandbox: Delete `CloseableResource`.

It's only used in once place. Just inline it.

* sandbox: `LedgerDao` no longer needs to be closeable.

* sandbox: Delete implicit materializers where they're not used.

* http-json: Wait for the Sandbox to start in tests.

* sandbox: Convert `scheduleHeartbeats` into a ResourceOwner.

* reference-v2: Explain why we steal ownership of the actor system.

* sandbox: Document why we only release resources once.

* sandbox: Add clues to ResourceOwnerSpec.

* http-json: Fix HttpServiceTestFixture to pass auth service through.

* codegen-sample-app: In ScalaCodeGenIT, wait for the server to  start.
2019-12-22 15:05:55 +00:00
Stefano Baghino
48d2fa1e1a Nuke //ledger/ledger-api-integration-tests (#3919) 2019-12-20 15:44:28 +00:00
Stefano Baghino
7020ed3b15
Moves CommandCompletionIT to Ledger API Test Tool (#3901)
* Moves CommandCompletionIT to Ledger API Test Tool

Closes #2841

Also refactors test observers into a single API and unifies the existing implementations of the DirectExecutionContext

* Allow explicit offsets to get checkpoints

* Raise checkpoint test timeout

* Consolidate checkpoint tests in a single test case

* Fix compilation issues

* Exclude command submission/completion tests for rev-v2

* Drop test not relevant for Ledger API implementations

* Fix compilation errors
2019-12-20 15:55:23 +01:00
Stefano Baghino
822ce28e75
Port command/transaction checks to Ledger API Test Tool (#3917)
Closes #2842
Closes #2843

The separation between high-level and low-level is not particularly meaningful, as the low-level variant issues commands with a component used by the high-level variant.
The separation aims at performing integration tests at two different levels but this can be addressed by a single suite of integration tests and relying on unit testing for individual components.

The first two tests:

- 'having many transactions all of them has a unique event id' reads transactions from an empty ledger and doesn't really test anything, so this has been dropped because the uniqueness of event identifiers is already more than covered by many tests in the 'TransactionService' suite.
- 'handle bad Decimals correctly' ensures the ledger api rejects unrepresentable decimals and it have been re-implemented as 'Reject unrepresentable numeric values' in the 'CommandService' suite.

The other tests are about command-and-exercise:

- 'process valid commands with workflow ids successfully' -> 'Implement create-and-exercise correctly'
- 'fail for invalid create arguments' -> 'Fail create-and-exercise on bad create arguments'
- 'fail for invalid choice arguments' -> 'Fail create-and-exercise on bad choice arguments'
- 'fail for an invalid choice' -> 'Fail create-and-exercise on invalid choice'
2019-12-20 13:24:55 +01:00
Stefano Baghino
6ece2b4147
Port backpressure tests to Sandbox integration tests (#3910)
Closes #2847
2019-12-20 13:22:18 +01:00
Brian Healey
9f13a2fb10 Upgrade to Akka 2.6.1, akka-http 10.1.11 and Scala 2.12.10 (#3903)
* Upgrade to Akka 2.6.1, akka-http 10.1.11 and Scala 2.12.10

Akka 2.6.1 Upgrade Changes
- Materializer in place of ActorMaterializer
- Source.future instead of Source.fromFuture
- The Scheduler.schedule method has been deprecated in favor of selecting scheduleWithFixedDelay or scheduleAtFixedRate
- onDownstreamFinish(cause: Throwable)
- ActorAttributes.supervisionStrategy(...) in place of ActorMaterializerSettings.withSupervisionStrategy

See https://doc.akka.io/docs/akka/current/project/migration-guide-2.5.x-2.6.x.html

* Akka 2.6.1 Upgrade Changes
- onDownstreamFinish(cause: Throwable)

See https://doc.akka.io/docs/akka/current/project/migration-guide-2.5.x-2.6.x.html

* code review: remove unnecessary supervision strategy
2019-12-19 18:00:59 +00:00
Samir Talwar
752e15bfb7 Sandbox: Test RecoveringIndexer logs, and stop dumping them to STDERR. (#3891)
* sandbox: Fix warnings in RecoveringIndexerSpec.

* sandbox: Test RecoveringIndexer logs, and stop dumping them to STDERR.

Printing logs during test execution is really annoying. This stubs the
logger factory with a TestNamedLoggerFactory which captures them in a
list instead, for testing purposes.

* sandbox: Remove unnecessary comments from {,Simple}NamedLoggerFactory.

* ledger-api-common: Remove unused parts of the NamedLoggerFactory.
2019-12-19 15:39:05 +00:00
Stefano Baghino
9f16d2de43 Fix WallClockTimeIT sandbox configuration (#3907)
Using the default configuration as a base for this test meant binding on 6865 instead of using dynamic port binding, which could cause flaky errors if some other test is occupying the port
2019-12-19 14:06:05 +00:00
Moritz Kiefer
c48b0ee289 Move Any wrappers and Archive to stable packages (#3890)
* Move Any wrappers and Archive to stable packages

There are no actual API or functionality changes in this PR but the
logic for locating the stable packages has slightly changed since the
Any wrappers package only makes sense for LF 1.7. To address this, we
simply filter out stable packages for newer LF versions since it
doesn’t make sense to depend on those anyway.

CHANGELOG_BEGIN

- [DAML Compiler] Move ``Archive`` type to a separate DALF.

CHANGELOG_END

* More comments

* Fix java codegen tests

* fix more tests

* Force cache reset on Windows

* Revert "Force cache reset on Windows"

This reverts commit 9f2b7d70b2.
2019-12-19 01:26:38 +00:00
mziolekda
7b882e3767
clean up kv metric names (#3888)
* clean up kv metric names

* rename metrics committing->committer

* replace camel-case with prometheus-friendly underscore
2019-12-18 14:27:07 +01:00
Stefano Baghino
af90d634fd Add CommandSubmissionCompletion suite to test tool (#3885) 2019-12-18 09:45:21 +00:00
mziolekda
2fd8372f44
fix indexer crash on duplicate submission (#3847)
* fix indexer crash on duplicate submission

* deduplicate submissions

* few formatting changes

* address review comments

* add pruning comment to dedup value
2019-12-18 09:14:49 +01:00
Moritz Kiefer
4ad3a22c90
Bump timeout in CommandClientIT (#3879)
This test suite was introduced in #3870 and seems to be extremely
flaky both locally (I get about 16/20 failures) and on CI.

The error is

  - should return completions of commands that are submitted after subscription *** FAILED *** (4 seconds, 945 milliseconds)
    Set() did not contain all elements of List("5104", "5100", "5105", "5109", "5103", "5106", "5107", "5102", "5108", "5101") (CommandClientIT.scala:330)

After bumping the timeout, I don’t get any failures locally.

Happy to choose another timeout, I have no clue what a sensible value
is here.
2019-12-18 09:11:47 +01:00
Stefano Baghino
f864ac955b
Port FailingCommandsIT to the Ledger API Test Tool (#3877)
* Port FailingCommandsIT to the Ledger API Test Tool

Closes #2850

The FailingCommandsIT suite contains tests for mismatching ledger
identifier (which is already abundantly covered by the Ledger API Test
Tool) and for bad labels in contract creation, both via submit and
submitAndWait.

Some of the tests previously part of the CommandService Ledger API Test
Tool suite have been moved to a new home in CommandSubmissionCompletion
to reflect the fact that those use the submission/completion workflow
instead of leveraging the submit-and-wait alternatives.

There are also suites that for some reason cover subsequent invocations
of the same services but I'm not sure of the meaning of those and I
would drop them, unless we have a good explanation for those.

* Optimize imports
2019-12-18 09:11:02 +01:00
Stefano Baghino
3ef2b2181d
Move CommandStaticTimeIT to Sandbox integration tests (#3874)
* Move CommandStaticTimeIT to Sandbox integration tests

Closes #2848

* Address https://github.com/digital-asset/daml/pull/3874#discussion_r358803654

* Address https://github.com/digital-asset/daml/pull/3874#discussion_r358802902
2019-12-17 17:01:46 +01:00
Stefano Baghino
699fef1f3a
Move Scala Ledger API client integration tests (#3870)
* Move Scala Ledger API client integration tests

Closes #2845

The Scala Ledger API client tests belong to the
//ledger/ledger-api-client package.

* Reduce noise coming from tests
2019-12-17 16:11:27 +01:00
Stefano Baghino
db711d40f3
Remove dead ledger-api-integration-tests code (#3866) 2019-12-16 18:01:42 +01:00
Samir Talwar
71e8c20127 Sandbox: Fix warnings in SandboxServer. (#3853)
* sandbox: Move SandboxServer's helper classes to the companion object.

And make them `private`, `final`, and non-`case`.

* sandbox: Drop SandboxServer.apply and just call the constructor.

* sandbox: Move the SandboxServer#SandboxState class into the object.

Leave the `resetAndRestartServer` method behind, though.
2019-12-14 20:52:03 +00:00
Stefano Baghino
3ca7ed49dd Remove warts: ExplicitImplicitTypes (#3851)
* Remove warts: ExplicitImplicitTypes

* Fix compilation errors
2019-12-13 18:33:49 +00:00
Stefano Baghino
d2c7067314 Rename weirdly named directories (#3850) 2019-12-13 18:32:11 +00:00
Jussi Mäki
33c7a1aace Implementation for the configuration management service (#3756)
* Implementation for the configuration management service

- Add configuration generation to the response of SetTimeModel
- Implement the ConfigManagementService
- Implement integration test into test tool

This is still a draft as it has unsolved FIXMEs and
it conflicts with #3744 which should go first.

The main conflict is with changes to PartyAllocationResponse which cannot
no longer reference "domain.PartyDetail" as we would have a cyclic dependency
(participant-state contains Configuration which we point to from domain.ConfigurationEntry).

The still open issues are:
- Revisit PartyDetail
- Naming: LedgerConfigurationService and ConfigManagementService are not talking
  about the same configuration and it feels confusing.
- Remove duplication of ConfigurationEntry? Do we need both domain.ConfigurationEntry
  and ledger.store.ConfigurationEntry? Only difference is in the types of participantId
  and submissionId.

* Address review part 1

* Fix up tests after rebase and address PR review

* Post-merge fixes

* Add missing config MRT checks and fixes to tests

- Check config MRT in InMemoryLedger and SqlLedger
- Use proper source of time in ConfigManagement
- Separate out ConfigManagementServiceIT in sandbox conformance tsets

* Reformat
2019-12-13 17:58:44 +00:00
Stefano Baghino
d7e734b744 Move ResetServiceIT to Sandbox integration tests (#3844)
Closes #2857

- Also deals with the long ignored todo about not using the context
- Attempts at restoring this as a non-flaky test
- Attempts at running the same test across runtime environments
2019-12-13 16:18:02 +00:00
Stefano Baghino
651384ad79
Perf tests no longer depend on integration tests (#3842)
* Perf tests no longer depend on integration tests

The infrastructure necessary to run performance tests on both the
in-memory and the persistent sandbox is duplicated to the
//ledger/sandbox-perf package in order to be able to get rid of all
contents of //ledger/ledger-api-integration-tests once the test porting
is over (which will happen soon).

The scope and functionality of ported classes has been reduced to the
minimum set needed by the performance test suite.

* Address https://github.com/digital-asset/daml/pull/3842#discussion_r357652888

* Address https://github.com/digital-asset/daml/pull/3842#discussion_r357653331

* Address https://github.com/digital-asset/daml/pull/3842#discussion_r357654770
2019-12-13 17:04:26 +01:00
Oliver Seeliger
b967a7d8c6 Test tool flakiness take2 (#3843)
* Ledger api test tool flakiness fix part 2: Add "eventually"

to synchronize use of waitForParties

* Upgrade to Canton 0.5.2
2019-12-13 13:37:02 +00:00
Samir Talwar
014b5608c2 Sandbox / Reference v2: Close the Ledger API Server on failure. (#3837)
* sandbox: No point creating a class just for the `close` method.

The LedgerApiServer class doesn't actually have much behavior apart from
closing. The `startServer` method is called during construction, which
definitely counts as spooky action at a distance. This change moves that
behavior to `LedgerApiServer.start` (renamed from `LedgerApiServer
.create` to make it more explicit).

There's not much point creating a class for the rest, so all behavior is
now in that `start` method.

* sandbox: Build up a list of "closeables" as the LedgerApiServer starts.

* sandbox: If the LedgerApiServer fails to come up, stop the parts.

* sandbox: Apply @stefanobaghino-da's refactoring suggestions.

* sandbox: Don't log while building the gRPC server; log at the end.

* sandbox: Turns out we should not stop the server when it works.

Facepalm.
2019-12-13 12:36:00 +00:00
Oliver Seeliger
2afd8bc55f Test tool party flakiness fix (#3841)
* Ledger api test tool party flakiness for multi-participant runs

Caused by synchronize not waiting for parties to fully exist on
all participants.

* Reenable canton test run

* Update canton to 0.5.2

* Revert "Update canton to 0.5.2"

This reverts commit d0e530c652.
2019-12-13 11:25:18 +00:00
Stefano Baghino
8965c1bf3b
Move TimeServiceDisabledIT to the sandbox integration tests (#3840)
Closes #2859
2019-12-13 11:53:27 +01:00
Jussi Mäki
ce70ad4a2f
Async package management (#3806)
* Add package_entries table

* Change PublicPackageUpload event to cover list of packages.

Add PublicPackageUploadRejected.

* Produce new package update events in KeyValueConsumption

* Update signature of uploadPackages

* Cleanup InMemoryKVParticipantState. Add submissionId to uploadPackages.

* Fix up InMemoryKVParticipantStateIT

* Initial ledger dao changes for package entries

Drop the participant_id as we never expect to see
entries of other participants. This should be done
for party_entries as well.

* Drop UploadPackagesResult

* Implement getPackageEntries and refactor callers

* Add maxRecordTime to uploadPackages

* First cut at updating ApiPackageManagementService

* Update tests, wire through the packageEntries

* Don't extend IndexPackagesService in InMemoryPackageStore

It does not implement the full interface and it isn't used
directly as one anyway.

* Drop maximum_record_time from package_management_service

Adding maximum record times touches the whole stack. Leaving
this change to another PR.

* Wire through the removal of maximum_record_time.

And remove dead code from InMemoryKVParticipantState

* Remove checking for duplicate package uploads

This aligns with the behaviour of WriteService.

* Reformat

* Fix PackageManagementService after adding of submission_id to the service
2019-12-13 09:56:47 +01:00
Gary Verhaegen
2b3693bf4d
restore 0.13.38 logging defaults for daml jars (#3819)
CHANGELOG_BEGIN
- [Sandbox] Restore 0.13.38 logging behaviour.
- [Navigator] Restore 0.13.38 logging behaviour.
- [Extractor] Restore 0.13.38 logging behaviour.
- [Internals] As of 0.13.39, we merged a number of internal JAR files in
  the SDK tarball to reduce its size. These jars used to be standalone
  JARs you could invoke as e.g. ``java -jar sandbox.jar <args>``. As a
  result of merging the jars, they lost their individual ``logback.xml``
  configuration file. Although running the jars directly was (and is
  still) not supported, note that you can now achieve the same behaviour
  with e.g. ``java -Dlogback.configurationFile=sandbox-logback.xml -jar
  daml-sdk.jar sandbox <args>``.
CHANGELOG_END
2019-12-12 14:02:23 +01:00
Samir Talwar
d7a7a78083 sandbox/reference-v2: Split Config into three. (#3823)
* sandbox/reference-v2: Split `Config` into three.

- Reference v2 CLI configuration
- Standalone API server configuration
- Standalone indexer configuration

* reference-v2: Simplify CLI parsing of TLS config and extra participants.

Turns out we _always_ want to support extra participants. They're
optional, after all.
2019-12-12 11:48:17 +00:00
Samir Talwar
90416744e4 sandbox: Re-add the Docker images with a public base image. (#3814)
* Revert "Remove docker bazel target for sandbox (#3802)"

This reverts commit 48a381ca49.

* sandbox: Use the public `openjdk` Docker image rather than GCR's.

Turns out you need to authenticate with Google Container Registry
regardless of whether the image is public or not. We don't want people
to have to bother logging in to GCR just to get Bazel working.
2019-12-11 16:58:08 +00:00
Samir Talwar
9ffa9b7aef sandbox: Delete unused test helpers. (#3820) 2019-12-11 16:11:07 +00:00
mziolekda
ac47a84085
clean up logs and metrics in the kvutils transaction processing (#3811)
* clean up logs and metrics in the kvutils transaction processing

* fix failing test
2019-12-11 15:36:12 +01:00
Samir Talwar
1184ee6f0a Sandbox: Split the Ledger API server and Indexer into separate packages. (#3783)
* sandbox: Split the StandaloneApiServer from the StandaloneIndexerServer.

* sandbox: Move StandaloneApiServer's nested classes to its companion.

And make them private.

* reference-v2: Rename `IndexServer` to `ApiServer`.

* sandbox: Move the services into the `apiserver.services` package.

* sandbox: Move SandboxEventIdFormatter's vals to the top.

* sandbox: StandaloneApiServer helper classes don't need to be Products.

* docs: Fix links for LedgerApiServer and Standalone{Api,Indexer}Server.

* sandbox: Delete a misleading comment from `StandaloneApiServer`.

* sandbox: Rename SandboxEventIdFormatter to EventIdFormatter.
2019-12-11 13:23:39 +00:00
Gerolf Seitz
48a381ca49 Remove docker bazel target for sandbox (#3802) 2019-12-10 15:43:12 +01:00
mziolekda
3c48bd37eb
Clean up kvutils logs (#3780)
* clean up

* clean up config committer

* remove unnecessary constructor parameters in the ConfigCommitter

* address review comments
2019-12-10 11:12:19 +01:00
Moritz Kiefer
e769264ddf Move all datatypes out of daml-prim (#3791)
* Move all datatypes out of daml-prim

This moves the remaining two modules DA.Types and GHC.Tuple to
separate LF packages with stable identifiers.

The only data types remaining are the ones for typeclasses which will
disappear once we move this to type synonyms.

CHANGELOG_BEGIN

- [DAML Compiler] The modules DA.Types and GHC.Tuple from daml-prim
have been moved to separate packages.

CHANGELOG_END

* Fix codegen tests

* Fix DarReader test

* Fix kvutils tests

* Fix jdbcdao tests

* Fix hs ledger bindings tests
2019-12-10 09:19:16 +01:00
Robert Autenrieth
bf2098f038
Check ledger and participant ID in claims (#3781)
* Add ledger and participant ID to claims

CHANGELOG_BEGIN
- [Ledger] AuthService implementations can now restrict the validity of access tokens to a single ledger or participant.
- [Sandbox] The sandbox JWT authentication now respects the ledgerId and participantId fields of the token payload.

CHANGELOG_END

* Add tests for ledger and participant in claims

* Address review comment

* Address review comment

* Fix tests

* Fix tests
2019-12-09 17:55:17 +01:00
Samir Talwar
639eba2c17 ledger-api-scala-logging: Fix errors in IntelliJ IDEA. (#3785)
* ledger-api-scala-logging: Fix errors in IntelliJ IDEA.

The Bazel plugin for IntelliJ doesn't seem to be smart enough to be able
to handle a Scala library that is part `src` directory and part
generated code from another Bazel rule. It just ignores the second part.
This means that IntelliJ cannot find the *ServiceLogging classes, as
they're not represented on the Bazel-generated classpath, and so
complains with lots of errors when working on the equivalent Api*Service
files.

To fix this, we can split these in two, compiling the base traits to
`ledger-api-scala-logging-base` and then the generated code separately.

It does result in an extra Bazel dependency for the users of
ledger-api-scala-logging, as Bazel doesn't realise transitive
dependencies for us.

* Release: Add `ledger-api-scala-logging-base` to the Maven list.
2019-12-09 16:02:59 +00:00
Samir Talwar
1033e48cb4
Ledger: Documentation for health checks. (#3779)
* ledger: Document the health checks.

* sandbox: Build a Docker image.

* sandbox: Create a sample Kubernetes YAML file.

* sandbox: Add health probes to the sample Kubernetes configuration file.

Startup and liveness are tested with a simple TCP connection to port
6865. Readiness checks are done with `grpc-health-probe`, which is added
to the Sandbox container image.

* sandbox: Link to kubernetes.yaml in the README and provide a disclaimer.

// changelog removed as it's not actually relevant to users

* sandbox: Don't try and build `sandbox-image-base` on Windows.

* Apply suggestions from code review

Co-Authored-By: Stefano Baghino <43749967+stefanobaghino-da@users.noreply.github.com>
2019-12-09 12:43:20 +01:00
Samir Talwar
1d1c7e9033 sandbox: Increase the timeout in StaticTimeIT. (#3774)
It's currently quite flaky in CI; I think increasing it a little will
help.

Also fixes some warnings in the same file.
2019-12-09 07:53:40 +00:00
Samir Talwar
732c675e76 Sandbox: Perform JDBC health checks on a timer. (#3773)
* sandbox: HikariJdbcConnectionProvider.start(), rather than construction.

It's too easy to construct things; I'd like it to be obvious that we're
starting something (in this case a connection pool).

* sandbox: In SqlLedgerSpec, stop ledgers before shutting down PostgreSQL.

* sandbox: Perform JDBC health checks on a timer.

The problem with hooking into existing requests is that if the Sandbox
is running in a load balancer and reports itself as unhealthy, it might
be taken out of the load balancer. Without any requests going through,
it'll never realize it's healthy again, and so will remain thinking it's
unhealthy forever.
2019-12-06 17:25:11 +00:00
Samir Talwar
b7fdf2236c sandbox: Merge DbDispatcher and SqlExecutor. (#3753)
* sandbox: Inline SqlExecutor into DbDispatcher.

There's no clear delineation of responsibilities. I'll try and separate
some of this back out again later.

* sandbox: Make it clear that we're "starting" the DbDispatcher.

* sandbox: Simplify the promise-based behavior in DbDispatcher.

* sandbox: Rename `noOfShortLivedConnections` to `maxConnections`.
2019-12-06 15:09:58 +00:00
Gerolf Seitz
e1a59776a7 Increase party allocation timeout and mark test as flaky (#3768)
The timeout for witnessing the party allocation is now increased
to 30 seconds (from 10 seconds). Additionally the LotsOfParties
conformance test is marked as flaky.
2019-12-06 14:34:23 +00:00
Gerolf Seitz
17435d6e99 Sandbox: Remove streaming connections (#3682)
* Sandbox: Remove streaming connections

The separate database connection pool for streaming connections
was only used for the active contracts stream. However, a single
db connection was being occupied until the last active contract was
streamed over the Ledger API to the client. This effectively means
that only ever 2 concurrent active contract streams could exist.
No need to say that this is bad design.

The following changes happened:

- remove the db connection pool for streaming connections
- replace the streaming mechanism for active contracts with
  the already existing pagination mechanism in JdbcLedgerDao
- change the pagination mechanism to actually use database level
  limit and offset instead of doing the pagination "client side"
- configure the HikariDataSource with the metric registry

CHANGELOG_BEGIN
- [Sandbox] Improve loading of active contracts for the Sandbox SQL backend.
CHANGELOG_END

* Extract PaginatingAsyncStream from JdbcLedgerDao for testing

* Reset metrics registry before each test
2019-12-06 10:58:10 +00:00
Oliver Seeliger
655d3d6716 Disable multi-participant ledger api test by default (#3761) 2019-12-06 10:56:32 +00:00
Brian Healey
71205e1f78 Include party allocation related events in integrity check (#3758) 2019-12-06 09:22:52 +01:00
Gerolf Seitz
0c00b28c83
Party management (#3744)
* Implement Async party allocation

* Address Jussi's review.

- Remove comments about implicit party entries
- Remove PollingUtils#pollSingleUntilPersisted
- Remove ill-placed comment in SqlLedger

Review: https://github.com/digital-asset/daml/pull/3744#pullrequestreview-327453144

* Address Samir's review

- Slight improvement in InMemoryKVParticipantStateIT
- Fix typo in scaladoc
- Fix SqlLedgerSpec: remove unused param and rephrase clues

Review: https://github.com/digital-asset/daml/pull/3744#pullrequestreview-327461368

* Address Stefano's review

Review: https://github.com/digital-asset/daml/pull/3744#pullrequestreview-327455206

* Only poll from the ledger end just before submitting the party allocation request.
2019-12-05 17:50:21 +01:00
Samir Talwar
cb378017d9 sandbox: If the Flyway migrations fail, crash the process. (#3731)
* sandbox: If the Flyway migrations fail, crash the process.

Otherwise running it in the background can make it look like
everything's OK.

* reference-v2: If the Flyway migrations fail, crash the process.

Otherwise running it in the background can make it look like
everything's OK.

* sandbox: Remove an errant debugging `println`.

* sandbox: Use `DirectExecutionContext.implicitEC`.
2019-12-05 13:44:13 +00:00
mziolekda
68fc7de296
Refactor kv party allocation committer (#3701)
* convert party allocation to the new committer pattern

* scalafmt

* Use map with optional values for kvutils input state

We need to do this to detect when a submission has maliciously
omitted an input key.
2019-12-05 08:22:39 +01:00
Moritz Kiefer
ba30e86911
Split wired-in modules into separate LF packages (#3696)
This is a first step towards making sure that the package ids for
types defined in daml-prim and daml-stdlib don’t change. This PR
mostly adds all the necessary infrastructure for that and moves
GHC.Types and GHC.Prim to make sure it works.

Until data-dependencies are really solid and we have verified that we
no longer have performance issues with an increasing number of Haskell
packages, we still include the source files in daml-prim and then just
rewrite the references.

We will also need to add tests that these packages really have stable
ids but I’ll leave that for separate PRs since this doesn’t make that
much sense anyway until all of the types have moved to stable
packages.

CHANGELOG_BEGIN

- [DAML Compiler] The modules GHC.Prim and GHC.Types from daml-prim
have been moved to separate packages.

CHANGELOG_END
2019-12-04 16:42:48 +01:00
Jussi Mäki
95ddb65483
DAML Engine: accurate package dependency annotations (#3726)
* Track used packages during whole of engine submit

- Introduce MutableCompiledPackages interface
- Add TrackingCompiledPackages that tracks fetched packages
- Make used packages in transaction optional to distinguish between
  missing dependencies and empty set of dependencies.

* Reimplement package dependency tracking

- Compute direct dependencies of a package during decoding
- Compute transitive dependencies of a package when adding a package
  to engine.
- Annotate the resulting transaction with package dependencies
  in Engine.submit.

* Create Ast.Package with proper direct deps in scenario service

While we don't have use for direct dependencies of a package in
scenario service (only Engine.submit needs it), it's better to be
accurate.

This of course overapproximates the direct dependencies.

* Compile a each new package once in ConcurrentCompiledPackages
2019-12-04 15:01:21 +01:00
Stefano Baghino
9e2d0127f2 Fix comment explaining required claims for services (#3727)
Addresses https://github.com/digital-asset/daml/pull/3721#discussion_r353644232
2019-12-04 13:33:17 +00:00
Stefano Baghino
36da75e1d6
Add authentication support to Java command completion client (#3713)
* Add authentication support to Java command completion client

* Address https://github.com/digital-asset/daml/pull/3713#discussion_r353629606
2019-12-04 11:31:21 +01:00
Stefano Baghino
de0c3db1a1
Restore optional endpoints but adds check (#3722)
* Revert "ledger-api-test-tool: The endpoints are mandatory. (#3611)"

This reverts commit 603ee9367b.

* Restore LedgerTestContext requirement

* Exit early if there are no participants to test
2019-12-04 10:14:59 +01:00
Oliver Seeliger
c1319451bf Fix submissionId typo in JdbcLedgerDao logging parameter (#3679) 2019-12-02 15:55:30 +00:00
Samir Talwar
5dd38d54e8 sandbox: PostgreSQL health checks. (#3655)
* ledger-api-test-tool: Increase the duration when watching health.

This should hopefully stop CI from flaking out.

* reference-v2/sandbox: Avoid unnecessary companion object constructors.

I like indirection… when it does something.

* ledger: Propagate empty health checks throughout the services.

* reference: Remove duplication from the ReferenceServer object.

* ledger-api-common: Actually query a "reporter" in the health service.

* ledger-api-common: Report health per-component when required.

* ledger-api-health: Use a Map to represent components for health checks.

* sandbox: Fix warnings in SqlLedgerSpec.

* ledger-api-common: Throw GrpcHealthService errors inside the Future.

* ledger: Implement health checks against the PostgreSQL connection.

Without proper testing, because I am not great at this.

* sandbox: Remove duplication and fix warnings in PostgresAround.

* sandbox: Test the SQL Ledger's health reporting on failure.

* sandbox: Don't report as unhealthy until 3 connections fail.

* ledger-api-health: Remove unused parts of the API.

Bit of premature design there.

* sandbox: Rename the "ledger" health check to "write".

* participant-state: Add the ReportsHealth trait to ReadService.

* ledger-api-common: `Future.fromTry(Try(…))` -> `Future(…)`.

* ledger-api-common: Make it clearer that StubReporter closes over health.

* ledger-api-common: Explain the HealthService watch tests with comments.

* sandbox: Clean up SqlLedger a bit.

* sandbox: Don't try and stop PostgreSQL twice in PostgresAround.

* bazel_tools: Windows rlocation lookups need to be with forward slashes.

* release: Fix case of "true".

* ledger-api-common: Make `GrpcHealthService::matchResponse` return a Try.

* ledger-api-common: Make `GrpcHealthServiceSpec` async.

* sandbox: Make a couple of DB classes final.

* sandbox: Avoid importing `X._` in PostgresAround.

* sandbox: Add clues to the SqlLedgerSpec's multiple assertions.

* sandbox: If PostgreSQL doesn't come back up, keep retrying.

* sandbox: Remove duplication in SqlLedgerSpec.

* sandbox: In SqlLedgerSpec, actually wait for the health to change.

* sandbox: In PostgresAround, make stopping PostgreSQL idempotent.

* sandbox: Simplify the SqlLedgerSpec to make it work on CI.

It's worth a shot.

* ledger-api-common: Simplify the GrpcHealthServiceSpec a little.

And add a changelog.

CHANGELOG_BEGIN

- [Ledger API Server] Add a health check endpoint conforming to the
  `GRPC Health Checking Protocol <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_.
- [Ledger API Server] Add health checks for index database connectivity.
- [Participant State API] Add a mandatory ``currentHealth()`` method to
  ``IndexService``, ``ReadService`` and ``WriteService``.

CHANGELOG_END

* sandbox: Improve the Javadoc layout for DbDispatcher.

* sandbox: Capitalize constants in SqlExecutor.

* ledger-api-health: Convert HealthStatus to an abstract class.
2019-11-29 15:07:43 +00:00
Oliver Seeliger
ef08936c05 Ledger api CommandService conformance test fixes (#3675)
Adding missing synchronize to two tests
2019-11-29 09:57:14 +00:00
nickchapman-da
d3d6891021
Rename daml lf tuples (#3658)
* Rename DAML-LF tuples as structs (structural records)
2019-11-28 07:58:30 +00:00
Samir Talwar
ae9bb35b85 ledger-api-test-tool: Increase the duration when watching health. (#3645)
This should hopefully stop CI from flaking out.
2019-11-27 13:23:38 -05:00
Brian Healey
02186ef068 Ledger configuration indexing changes (rebased to master) (#3553)
* Add participant-state configuration protobuf

- Move the "DamlConfiguration" from kvutils into participant-state/protobuf/ledger_configuration.proto.
- Add version number and spec (ala transaction.proto)

This is a preparation for indexing the configuration and having one canonical serialization for it.

* Initial thoughts on indexing the configuration

* Implement indexing of ledger configuration changes

* Add record time to all Updates. Wire through participant id.

and rename V7__Add_configuration to V8.

* Add ledger_configuration_java_proto to release artifacts

* Fix up release of ledger_configuration_java_proto

* Suggestions from review

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* Apply suggestions from code review

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* address rebase issues

* Resolve compilation errors after rebase/merge

* happy formatting for scala and bazel and friends

* Drop "openWorld" setting from configuration

And refactor the tests to allocate parties explicitly.

* Fix up migration and tests

* Drop authorizedParticipantIds from configuration

Implement configuration authorization in kvutils using the previous
the participant id of the previous configuration.

* Post-rebase fixes

* Add missing migrations

* Apply suggestions from code review

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* Add missing mavenUpload to ledger-api-server

* Remove stateUpdateRecordTime

* Address code review

- Address PR review
- Merge TimeModelImpl and the traits. Remove TimeModel from ledger-api-common.
- Throw `Err` from KeyValueConsumption on parse errors instead of assert/sys.error

* Reformat

* Add missing protobuf file

* Fix compilation after TimeModel changes. Add version logs to participant-state{,-kvutils}.

* Fix TestUtil.scala build

* Apply suggestions from code review

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* Address review

- synchronized access to ledgerConfiguration in InMemoryLedger
- store rejection if configuration generation is wrong

* Update ledger/participant-state/protobuf/ledger_configuration.rst

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>
2019-11-27 17:41:23 +01:00
Stefano Baghino
3482ffac19 Fix wrong token usage in auth tests (#3648) 2019-11-27 10:48:39 +00:00
Stefano Baghino
4d922e763b Add authentication to Java identity client (#3630)
* Add authentication to Java identity client

Contributes to #3626

No changelog added right now, it will be added with the PR that
effectively closes the ticket.

Moves `LedgerCallCredentials` to a shared package.

Establishes the test framework for other Java clients.

* Address https://github.com/digital-asset/daml/pull/3630#discussion_r350663731

* Address https://github.com/digital-asset/daml/pull/3630#discussion_r350663731

* Rebase and fix compilation errors

* Fix type of jar in artifacts.yaml

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* Fix more errors emerged after rebase

* Add dependency for DAML assistant ITs

* Add missing dependency

* Fix wrong dependency

* fix release
2019-11-26 18:51:09 +00:00
Remy
06b7a106a1 DAML-LF: generic map values protobuf format (#3583)
* DAML-LF: generic map values protobuf format

* Apply suggestions from code review

Co-Authored-By: Gerolf Seitz <gerolf.seitz@digitalasset.com>

* Address Gerolf's comment

* Apply suggestions from code review

Co-Authored-By: Stephen Compall <stephen.compall@daml.com>

* fix test

* Address Stephen's last comment
2019-11-26 13:34:33 +00:00
Stefano Baghino
3d3322a06a
Fix wording in authorization tests (#3629)
Address previously unaddressed https://github.com/digital-asset/daml/pull/3598#discussion_r350581428
2019-11-26 11:12:30 +01:00
Stefano Baghino
160da16227
Move AuthorizationIT to sandbox integration tests (#3598)
* Move AuthorizationIT to Sandbox ITs

* Use refactored code in Extractor

* Apply a few improvements, see body

- Run previously ignored tests
- Make token signing private
- Fix stream observer utility comment more accurate
- Add read-only token helper

* Add r/w token split tests

* Fix formatting and imports

* Address https://github.com/digital-asset/daml/pull/3598#discussion_r349769546

* Address https://github.com/digital-asset/daml/pull/3598#discussion_r349769801

* Fix inaccurate test

A test was incorrectly trying to get a token with an invalid signature

* Address reviews
2019-11-26 10:13:36 +01:00
Samir Talwar
8818ea7cbb kvutils: Clean up the InMemoryKVParticipantState integration tests a little. (#3621)
* kvutils: Nest all InMemoryKVParticipantState tests inside the block.

* kvutils: Simplify InMemoryKVParticipantStateIT where possible.

* kvutils: In InMemoryKVParticipantStateIT, move assertions to the end.

It's confusing when the assertions are before the submissions.

* kvutils: Move test helpers into a companion object.

* kvutils: Use BeforeAndAfterEach in testing to remove duplication.

* kuvtils: In testing config updates, always increment the generation.

* kvutils: Assert something in the "initial conditions" integration test.
2019-11-25 17:49:56 -05:00
Samir Talwar
8df4b9ec33 ledger-api-test-tool: Use the default Akka execution context. (#3608)
* ledger-api-test-tool: Use the default Akka execution context.

Akka will use the global fork-join pool by default, which is fine for
our purposes. There's no longer a need to use a specific execution
context, because we no longer use it to limit the work in progress.
That's now done by the parallelism parameter to Akka Streams'
`mapAsyncUnordered`.

* ledger-api-test-tool: Shut down the ActorSystem.
2019-11-25 15:57:17 +00:00
Samir Talwar
603ee9367b ledger-api-test-tool: The endpoints are mandatory. (#3611)
We should fail fast if no endpoints are provided, rather than timing out
every test.
2019-11-25 15:32:35 +00:00
Robert Autenrieth
4c3f6014f6
Implement support for RSA-signed JWT tokens (#3526)
* Improve Navigator output

* Fix Navigator not using the access token

* Add RSA signatures for JWT tokens

* Remove unused method

* Add timeouts for reading JWKS

* Fix test

* Rename method for consistency

* Improve comment

* More renaming for consistency

* CHANGELOG

CHANGELOG_BEGIN
- [Sandbox] Add CLI options to start the sandbox with JWT based authentication with RSA signed tokens.
  See `issue #3155 <https://github.com/digital-asset/daml/issues/3155>`__ .
- [Navigator] Fixed a bug where the `--access-token-file` option did not work correctly.
CHANGELOG_END

* Make JwksVerifier limits configurable

* Make SimpleHttpServer private
2019-11-25 16:29:24 +01:00
Stefano Baghino
552bf6497d Obscure shared-secret-based authenticated sandbox (#3609)
The shared-secret-based authentication is there exclusively for testing,
this PR makes sure that this is correctly reported through the CLI and
hides this until further notice.

Makes sure that the flag clearly says that this option is not meant for
production use cases.

A warning is already printed when this feature is used, both at startup
and every time this verifier is used.

CHANGELOG_BEGIN

- [Sandbox] The ``--auth-jwt-hs256`` is renamed to
``--auth-jwt-hs256-unsafe``: you are advised to _not_ use this JWT token
signing way in a production environment.

CHANGELOG_END
2019-11-25 14:27:21 +00:00
Oliver Seeliger
26b569f73d Properly drop invalid actor name chars in standalone indexer actor name (#3604)
Closes #3327

CHANGELOG_BEGIN

[Ledger]
  * Allow non-alphanumeric characters in ledger api server participant ids (space, colon, hash, slash, dot). Proper fix for change originally attempted in v0.13.36. See issue `issue #3327 <https://github.com/digital-asset/daml/issues/3327>`__.

CHANGELOG_END

Proper fix replacing f39bf7fc5a which does not work
2019-11-25 11:16:59 +00:00
Samir Talwar
159104adb1 ledger-api-test-tool: Don't discard the cause on fail. (#3600)
* ledger-api-test-tool: On `fail`, don't discard the cause.

* ledger-api-test-tool: Delete a redundant `new`.
2019-11-25 10:43:01 +00:00
Oliver Seeliger
d35961d857
Ledger api test tool canton run config fix (#3602)
Missing from 15a7f72eae
2019-11-25 11:13:27 +01:00
Samir Talwar
1bd2ec5b1a grpc-utils: Simpler extractors. (#3594)
* grpc-utils: Simpler GrpcStatus extractors when you know the code.

And don't care about the description.

* grpc-utils: Simpler GrpcException extractors when you know the code.

And don't care about the description.

* Apply suggestions from code review

Co-Authored-By: Stefano Baghino <43749967+stefanobaghino-da@users.noreply.github.com>

* Add `new` to `SpecificGrpc{Exception,Status}` constructor calls.

Also, don't blindly apply GitHub suggestions.
2019-11-22 21:09:17 +00:00
Stefano Baghino
6d16409699 Move ReflectionIT out of LAPI IT (#3582)
* Move ReflectionIT out of LAPI IT

* Address https://github.com/digital-asset/daml/pull/3582#discussion_r349221189

* Address https://github.com/digital-asset/daml/pull/3582#discussion_r349507268

* Delete previous incarnation of the test
2019-11-22 16:30:56 +00:00
Samir Talwar
0ff716df2a Ledger API: Add healthcheck endpoints. (#3573)
* grpc-definitions: Delete health_service.proto

We can use the version in io.grpc:grpc-services instead.

* ledger: Delete ledger/API.md.

* sandbox: Fix warnings in ApiServices flagged by IntelliJ.

* sandbox: Implement a dummy grpc.health.v1.Health.Check endpoint.

* sandbox: Implement a dummy grpc.health.v1.Health.Watch endpoint.

* sandbox: Drop repeated elements from grpc.health.v1.Health.Watch.

* sandbox: Wrap the HealthService in basic tests.

* sandbox: Stop streaming the server health too.

* ledger-api-test-tool: Health check tests.

* Add a changelog entry for the health check endpoints.

CHANGELOG_BEGIN

- [Ledger API] Add healthcheck endpoints, conforming to the
  `GRPC Health Checking Protocol <https://github.com/grpc/grpc/blob/master/doc/health-checking.md>`_.
  It is always ``SERVING`` for now.

- [DAML Ledger Integration Kit] Add conformance test coverage for the
  ``grpc.health.v1.Health`` service.

CHANGELOG_END

* ledger-api-integration-tests: Increment the number of services.

* Apply suggestions from code review

Co-Authored-By: Stefano Baghino <43749967+stefanobaghino-da@users.noreply.github.com>

* sandbox: Use `AkkaBeforeAndAfterAll` in the HealthServiceSpec.

In an attempt to get it working on CI.

* sandbox: Change `dropRepeated` to `DropRepeated()`.

Keep it in one file.

* test-common: Use `Delayed.by` in `TimeBoundObserver`.

* test-common: Close the source when `TimeBoundObserver` completes.

* ./fmt.sh

That'll teach me not to `--no-verify` just because it's a merge commit.

* sandbox: Inline `HealthService.suppress`.

At some point it was being used twice.

* sandbox: Increase the timeout for HealthServiceSpec.

* sandbox: Reimplement HealthService using the Scala protobuf types.

* sandbox: Generate an Akka-compatible trait for the health service.

And refactor a lot of test code to make it easy to test.

* ledger-api-common: Move the HealthService here.

* rs-grpc-testing-utils: Publish to Maven.

* rs-grpc-testing-utils: Add Maven coordinates.
2019-11-22 14:02:05 +00:00
Oliver Seeliger
ad3adbb7aa
Ledger api test tool --load-scale-factor option to test different ledgers (#3586)
CHANGELOG_BEGIN

[DAML Integration Toolkit]
  * Add ledger api test tool `--load-scale-factor` option that allows dialing up
     or down the workload applied by scale tests (such as the
     `TransactionScaleIT` suite). This allows improving the performance of
     different ledger over time.

CHANGELOG_END
2019-11-22 14:51:17 +01:00
Remy
3f8bd0da5e DAML-LF: rename ValueMap to ValueTextMap. (#3584) 2019-11-22 11:35:32 +00:00
Robert Autenrieth
87c8f274e1
Split rw claims (#3548)
* Split read and write claims

Fixes #3398

CHANGELOG_BEGIN
- [Sandbox] Added support JWT tokens that only authorize to read data, but not to act on the ledger.
CHANGELOG_END
2019-11-22 11:24:50 +01:00
Stefano Baghino
9f9d2d0458 Move and improve LedgerIdentityService integration tests (#3581) 2019-11-21 17:08:10 +00:00
Gerolf Seitz
c43f004e57
Replace MetricsManager with MetricRegistry (#3574)
Instead of passing around MetricsManager just for the timedFuture
method, we pass the underlying MetricRegistry directly and use
the timedFuture function as an actual function (passing in a timer metric).

The Sandbox still starts the JmxReporter, but the integrator of the Indexer
and the Ledger API Server needs to enable the reporting facilities themselves.

CHANGELOG_BEGIN

- [Ledger] Ledger API Server and Indexer now accept an instance of ``MetricRegistry`` as parameters. This gives implementors of ledger integrations the most flexibility to set up metrics reporting that works best for them.

CHANGELOG_END
2019-11-21 16:47:30 +01:00
Stefano Baghino
f2f60d5e4c
Move LedgerConfigurationService out of Ledger API IT (#3576) 2019-11-21 16:02:17 +01:00