[
  {
    "path": ".gitignore",
    "content": "# sbt\nlib_managed\nproject/project\ntarget\n\n# Worksheets (Eclipse or IntelliJ)\n*.sc\n\n# Eclipse\n.cache*\n.classpath\n.project\n.scala_dependencies\n.settings\n.target\n.worksheet\n\n# IntelliJ\n.idea\n\n# ENSIME\n.ensime\n.ensime_lucene\n.ensime_cache\n\n# Mac\n.DS_Store\n\n# Akka Persistence\njournal\nsnapshots\n\n# Log files\n*.log\n"
  },
  {
    "path": ".scalafmt.conf",
    "content": "style = defaultWithAlign\n\ndanglingParentheses        = true\nindentOperator             = spray\nmaxColumn                  = 100\nproject.excludeFilters     = [\".*\\\\.sbt\"]\nrewrite.rules              = [RedundantBraces, RedundantParens, SortImports]\nspaces.inImportCurlyBraces = true\nunindentTopLevelOperators  = true\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: scala\n\nscala:\n  - 2.11.11\n  - 2.12.4\n\njdk:\n  - oraclejdk8\n\nsbt_args: -Dakka.test.timefactor=3.0\n\nsudo: required\n\nservices:\n  - docker\n\nbefore_install:\n  - docker run\n      --detach\n      --publish 2379:2379\n      quay.io/coreos/etcd:v2.3.7\n      --listen-client-urls http://0.0.0.0:2379\n      --advertise-client-urls http://127.0.0.1:2379\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "NOTICE",
    "content": "Copyright 2015 Heiko Seeberger\n"
  },
  {
    "path": "README.md",
    "content": "# ConstructR #\n\n[![Join the chat at https://gitter.im/hseeberger/constructr](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/hseeberger/constructr?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n\nConstructR is for bootstrapping (construction) an [Akka](http://akka.io) cluster by using a coordination service.\n\nDisambiguation: Despite the similar name, ConstructR is not related to [Lightbend ConductR](http://www.lightbend.com/products/conductr).\n\nConstructR utilizes a key-value coordination service like etcd to automate bootstrapping or joining a cluster. It stores each member node under the key `/constructr/$clusterName/nodes/$address` where `$clusterName` is for disambiguating multiple clusters and `$address` is a Base64 encoded Akka `Address`. These keys expire after a configurable time in order to avoid stale information. Therefore ConstructR refreshes each key periodically.\n\nIn a nutshell, ConstructR is a state machine which first tries to get the nodes from the coordination service. If none are available it tries to acquire a lock, e.g. via a CAS write for etcd, and uses itself or retries getting the nodes. Then it joins using these nodes as seed nodes. After that it adds its address to the nodes and starts the refresh loop:\n\n```\n                  ┌───────────────────┐              ┌───────────────────┐\n              ┌──▶│   GettingNodes    │◀─────────────│BeforeGettingNodes │\n              │   └───────────────────┘    delayed   └───────────────────┘\n              │             │     │                            ▲\n  join-failed │   non-empty │     └──────────────────────┐     │ failure\n              │             ▼               empty        ▼     │\n              │   ┌───────────────────┐              ┌───────────────────┐\n              └───│      Joining      │◀─────────────│      Locking      │\n                  └───────────────────┘    success   └───────────────────┘\n                            │\n              member-joined │\n                            ▼\n                  ┌───────────────────┐\n                  │    AddingSelf     │\n                  └───────────────────┘\n                            │     ┌────────────────────────────┐\n                            │     │                            │\n                            ▼     ▼                            │\n                  ┌───────────────────┐              ┌───────────────────┐\n                  │ RefreshScheduled  │─────────────▶│    Refreshing     │\n                  └───────────────────┘              └───────────────────┘\n```\n\nIf something goes finally wrong when interacting with the coordination service, e.g. a permanent timeout after a configurable number of retries, ConstructR terminates its `ActorSystem` in the spirit of \"fail fast\".\n\n``` scala\n// All releases including intermediate ones are published here,\n// final ones are also published to Maven Central.\nresolvers += Resolver.bintrayRepo(\"hseeberger\", \"maven\")\n\nlibraryDependencies ++= Vector(\n  \"de.heikoseeberger\" %% \"constructr\" % \"0.19.0\",\n  \"de.heikoseeberger\" %% \"constructr-coordination-etcd\" % \"0.19.0\", // in case of using etcd for coordination\n  ...\n)\n```\n\nSimply add the `ConstructrExtension` to the `extensions` configuration setting:\n\n```\nakka.extensions = [de.heikoseeberger.constructr.ConstructrExtension]\n```\n\nThis will start the `Constructr` actor as a system actor. Alternatively start it yourself as early as possible if you feel so inclined.\n\nThe following listing shows the available configuration settings with their defaults:\n\n```\nconstructr {\n  coordination {\n    host = localhost\n    port = 2379\n  }\n\n  coordination-timeout    = 3 seconds  // Maximum response time for coordination service (e.g. etcd)\n  join-timeout            = 15 seconds // Might depend on cluster size and network properties\n  abort-on-join-timeout   = false      // Abort the attempt to join if true; otherwise restart the process from scratch\n  max-nr-of-seed-nodes    = 0          // Any nonpositive value means Int.MaxValue\n  nr-of-retries           = 2          // Nr. of tries are nr. of retries + 1\n  refresh-interval        = 30 seconds // TTL is refresh-interval * ttl-factor\n  retry-delay             = 3 seconds  // Give coordination service (e.g. etcd) some delay before retrying\n  ttl-factor              = 2.0        // Must be greater or equal 1 + ((coordination-timeout * (1 + nr-of-retries) + retry-delay * nr-of-retries)/ refresh-interval)!\n  ignore-refresh-failures = false      // Ignore failures once machine is already in \"Refreshing\" state. It prevents from FSM being terminated due to exhausted number of retries.\n\n}\n```\n\n## Coordination\n\nConstructR comes with out-of-the-box support for etcd: simply depend on the \"constructr-coordination-etcd\" module. If you want to use some other coordination backend, e.g. Consul, simply implement the `Coordination` trait from the \"constructr-coordination\" module and make sure to provide the fully qualified class name via the `constructr.coordination.class-name` configuration setting.\n\n### Community Coordination Implementations\n\nThere are some implementations for other coordination backends than etcd:\n\n* [Tecsisa/constructr-consul](https://github.com/Tecsisa/constructr-consul): This library enables to use Consul as cluster coordinator in a ConstructR based cluster.\n* [everpeace/constructr-redis](https://github.com/everpeace/constructr-redis): This library enables to use Redis as cluster coordinator in a ConstructR based cluster.\n* [typesafehub/constructr-zookeeper](https://github.com/typesafehub/constructr-zookeeper): This library enables to use ZooKeeper as cluster coordinator in a ConstructR based cluster.\n\n## Testing\n\netcd must be running, e.g.:\n\n```\ndocker run \\\n  --detach \\\n  --name etcd \\\n  --publish 2379:2379 \\\n  quay.io/coreos/etcd:v2.3.8 \\\n  --listen-client-urls http://0.0.0.0:2379 \\\n  --advertise-client-urls http://192.168.99.100:2379\n```\n\n## Contribution policy ##\n\nContributions via GitHub pull requests are gladly accepted from their original author. Along with any pull requests, please state that the contribution is your original work and that you license the work to the project under the project's open source license. Whether or not you state this explicitly, by submitting any copyrighted material via pull request, email, or other means you agree to license the material under the project's open source license and warrant that you have the legal authority to do so.\n\nPlease make sure to follow these conventions:\n- For each contribution there must be a ticket (GitHub issue) with a short descriptive name, e.g. \"Respect seed-nodes configuration setting\"\n- Work should happen in a branch named \"ISSUE-DESCRIPTION\", e.g. \"32-respect-seed-nodes\"\n- Before a PR can be merged, all commits must be squashed into one with its message made up from the ticket name and the ticket id, e.g. \"Respect seed-nodes configuration setting (closes #32)\"\n\n## License ##\n\nThis code is open source software licensed under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0.html).\n"
  },
  {
    "path": "bin/run-etcd.sh",
    "content": "#!/usr/bin/env sh\n\n: ${HOST:=$(ipconfig getifaddr en0)}\n: ${HOST:=$(ipconfig getifaddr en1)}\n: ${HOST:=$(ipconfig getifaddr en2)}\n: ${HOST:=$(ipconfig getifaddr en3)}\n: ${HOST:=$(ipconfig getifaddr en4)}\nif [ -z $HOST ]; then\n  echo HOST neither defined nor detectable!\n  exit 1\nfi\n\ndocker run \\\n  --detach \\\n  --name etcd \\\n  --publish 2379:2379 \\\n  quay.io/coreos/etcd:v2.3.7 \\\n  --advertise-client-urls http://${HOST}:2379 \\\n  --listen-client-urls http://0.0.0.0:2379\n"
  },
  {
    "path": "build.sbt",
    "content": "// *****************************************************************************\n// Projects\n// *****************************************************************************\n\nlazy val constructr =\n  project\n    .in(file(\".\"))\n    .enablePlugins(GitVersioning)\n    .aggregate(core, coordination, `coordination-etcd`)\n    .settings(settings)\n    .settings(\n      unmanagedSourceDirectories.in(Compile) := Seq.empty,\n      unmanagedSourceDirectories.in(Test) := Seq.empty,\n      publishArtifact := false\n    )\n\nlazy val core =\n  project\n    .enablePlugins(AutomateHeaderPlugin)\n    .configs(MultiJvm)\n    .dependsOn(coordination,`coordination-etcd` % \"test->compile\")\n    .settings(settings)\n    .settings(multiJvmSettings)\n    .settings(\n      name := \"constructr\",\n      libraryDependencies ++= Seq(\n        library.akkaCluster,\n        library.akkaLog4j            % Test,\n        library.akkaMultiNodeTestkit % Test,\n        library.akkaTestkit          % Test,\n        library.log4jCore            % Test,\n        library.mockitoCore          % Test,\n        library.scalaTest            % Test\n      )\n    )\n\nlazy val coordination =\n  project\n    .enablePlugins(AutomateHeaderPlugin)\n    .settings(settings)\n    .settings(\n      name := \"constructr-coordination\",\n      libraryDependencies ++= Seq(\n        library.akkaActor\n      )\n    )\n\nlazy val `coordination-etcd` =\n  project\n    .enablePlugins(AutomateHeaderPlugin)\n    .dependsOn(coordination)\n    .settings(settings)\n    .settings(\n      name := \"constructr-coordination-etcd\",\n      libraryDependencies ++= Seq(\n        library.akkaHttp,\n        library.akkaStream,\n        library.circeParser,\n        library.akkaTestkit % Test,\n        library.scalaTest   % Test\n      )\n    )\n\n// *****************************************************************************\n// Library dependencies\n// *****************************************************************************\n\nlazy val library =\n  new {\n    object Version {\n      final val akka      = \"2.5.6\"\n      final val akkaHttp  = \"10.0.10\"\n      final val akkaLog4j = \"1.5.0\"\n      final val circe     = \"0.8.0\"\n      final val log4j     = \"2.9.1\"\n      final val mockito   = \"2.7.22\"\n      final val scalaTest = \"3.0.4\"\n    }\n    val akkaActor            = \"com.typesafe.akka\"        %% \"akka-actor\"              % Version.akka\n    val akkaCluster          = \"com.typesafe.akka\"        %% \"akka-cluster\"            % Version.akka\n    val akkaHttp             = \"com.typesafe.akka\"        %% \"akka-http\"               % Version.akkaHttp\n    val akkaLog4j            = \"de.heikoseeberger\"        %% \"akka-log4j\"              % Version.akkaLog4j\n    val akkaMultiNodeTestkit = \"com.typesafe.akka\"        %% \"akka-multi-node-testkit\" % Version.akka\n    val akkaSlf4j            = \"com.typesafe.akka\"        %% \"akka-slf4j\"              % Version.akka\n    val akkaStream           = \"com.typesafe.akka\"        %% \"akka-stream\"             % Version.akka\n    val akkaTestkit          = \"com.typesafe.akka\"        %% \"akka-testkit\"            % Version.akka\n    val circeParser          = \"io.circe\"                 %% \"circe-parser\"            % Version.circe\n    val log4jCore            = \"org.apache.logging.log4j\" %  \"log4j-core\"              % Version.log4j\n    val mockitoCore          = \"org.mockito\"              %  \"mockito-core\"            % Version.mockito\n    val scalaTest            = \"org.scalatest\"            %% \"scalatest\"               % Version.scalaTest\n}\n\n// *****************************************************************************\n// Settings\n// *****************************************************************************        |\n\nlazy val settings =\n  commonSettings ++\n  gitSettings ++\n  scalafmtSettings ++\n  publishSettings ++\n  multiJvmSettings ++\n  bintraySettings\n\nlazy val commonSettings =\n  Seq(\n    // scalaVersion from .travis.yml\n    // crossScalaVersions from .travis.yml\n    organization := \"de.heikoseeberger\",\n    organizationName := \"Heiko Seeberger\",\n    startYear := Some(2015),\n    licenses += (\"Apache-2.0\", url(\"http://www.apache.org/licenses/LICENSE-2.0\")),\n    scalacOptions ++= Seq(\n      \"-unchecked\",\n      \"-deprecation\",\n      \"-language:_\",\n      \"-target:jvm-1.8\",\n      \"-encoding\", \"UTF-8\"\n    ),\n    unmanagedSourceDirectories.in(Compile) := Seq(scalaSource.in(Compile).value),\n    unmanagedSourceDirectories.in(Test) := Seq(scalaSource.in(Test).value)\n)\n\nlazy val gitSettings =\n  Seq(\n    git.useGitDescribe := true\n  )\n\nlazy val scalafmtSettings =\n  Seq(\n    scalafmtOnCompile := true,\n    scalafmtOnCompile.in(Sbt) := false,\n    scalafmtVersion := \"1.3.0\"\n  )\n\nlazy val publishSettings =\n  Seq(\n    homepage := Some(url(\"https://github.com/hseeberger/constructr\")),\n    scmInfo := Some(ScmInfo(url(\"https://github.com/hseeberger/constructr\"),\n                            \"git@github.com:hseeberger/constructr.git\")),\n    developers += Developer(\"hseeberger\",\n                            \"Heiko Seeberger\",\n                            \"mail@heikoseeberger.de\",\n                            url(\"https://github.com/hseeberger\")),\n    pomIncludeRepository := (_ => false)\n  )\n\nlazy val bintraySettings =\n  Seq(\n    bintrayPackage := \"constructr\"\n  )\n\nlazy val multiJvmSettings =\n  com.typesafe.sbt.SbtMultiJvm.multiJvmSettings ++\n  inConfig(MultiJvm)(scalafmtSettings) ++\n  headerSettings(MultiJvm) ++\n  automateHeaderSettings(MultiJvm) ++\n  Seq(\n    unmanagedSourceDirectories.in(MultiJvm) := Seq(scalaSource.in(MultiJvm).value),\n    test.in(Test) := test.in(MultiJvm).dependsOn(test.in(Test)).value\n  )\n"
  },
  {
    "path": "coordination/src/main/scala/de/heikoseeberger/constructr/coordination/Coordination.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr.coordination\n\nimport akka.Done\nimport akka.actor.{ ActorSystem, Address }\nimport scala.concurrent.Future\nimport scala.concurrent.duration.FiniteDuration\n\nobject Coordination {\n\n  def apply(clusterName: String, system: ActorSystem): Coordination =\n    try {\n      val className =\n        system.settings.config.getString(\"constructr.coordination.class-name\")\n      Class\n        .forName(className)\n        .getConstructor(classOf[String], classOf[ActorSystem])\n        .newInstance(clusterName, system)\n        .asInstanceOf[Coordination]\n    } catch {\n      case _: NoSuchMethodException =>\n        throw new Exception(\n          \"\"\"|A Coordination implementation must provide a constructor with the following signature:\n             |(clusterName: String, system: ActorSystem)\"\"\".stripMargin\n        )\n    }\n}\n\n/**\n  * Abstraction for a coordination service. Implementations must provide a constructor with the following signature:\n  * `(prefix: String, clusterName: String, system: ActorSystem)`.\n  */\ntrait Coordination {\n\n  /**\n    * Get the nodes.\n    *\n    * @return future of nodes\n    */\n  def getNodes(): Future[Set[Address]]\n\n  /**\n    * Akquire a lock for bootstrapping the cluster (first node).\n    *\n    * @param self self node\n    * @param ttl TTL for the lock\n    * @return true, if lock could be akquired, else false\n    */\n  def lock(self: Address, ttl: FiniteDuration): Future[Boolean]\n\n  /**\n    * Add self to the nodes.\n    *\n    * @param self self node\n    * @param ttl TTL for the node entry\n    * @return future signaling done\n    */\n  def addSelf(self: Address, ttl: FiniteDuration): Future[Done]\n\n  /**\n    * Refresh entry for self.\n    *\n    * @param self self node\n    * @param ttl TTL for the node entry\n    * @return future signaling done\n    */\n  def refresh(self: Address, ttl: FiniteDuration): Future[Done]\n}\n"
  },
  {
    "path": "coordination-etcd/src/main/resources/reference.conf",
    "content": "constructr {\n  coordination {\n    class-name = de.heikoseeberger.constructr.coordination.etcd.EtcdCoordination\n    host       = localhost\n    port       = 2379\n  }\n}\n"
  },
  {
    "path": "coordination-etcd/src/main/scala/de/heikoseeberger/constructr/coordination/etcd/EtcdCoordination.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr.coordination\npackage etcd\n\nimport akka.Done\nimport akka.actor.{ ActorSystem, Address, AddressFromURIString }\nimport akka.http.scaladsl.Http\nimport akka.http.scaladsl.client.RequestBuilding.{ Get, Put }\nimport akka.http.scaladsl.model.StatusCodes.{ Created, NotFound, OK, PreconditionFailed }\nimport akka.http.scaladsl.model.{ HttpRequest, HttpResponse, ResponseEntity, StatusCode, Uri }\nimport akka.http.scaladsl.unmarshalling.Unmarshal\nimport akka.stream.ActorMaterializer\nimport akka.stream.scaladsl.Sink\nimport io.circe.Json\nimport io.circe.parser.parse\nimport java.nio.charset.StandardCharsets.UTF_8\nimport java.util.Base64.{ getUrlDecoder, getUrlEncoder }\nimport scala.concurrent.Future\nimport scala.concurrent.duration.{ Duration, FiniteDuration }\n\nobject EtcdCoordination {\n\n  final case class UnexpectedStatusCode(uri: Uri, statusCode: StatusCode)\n      extends RuntimeException(\n        s\"Unexpected status code $statusCode for URI $uri\"\n      )\n\n  private def toSeconds(duration: Duration) = (duration.toSeconds + 1).toString\n}\n\nfinal class EtcdCoordination(clusterName: String, system: ActorSystem) extends Coordination {\n  import EtcdCoordination._\n\n  private implicit val mat = ActorMaterializer()(system)\n\n  import mat.executionContext\n\n  private val kvUri = {\n    val host = system.settings.config.getString(\"constructr.coordination.host\")\n    val port = system.settings.config.getInt(\"constructr.coordination.port\")\n    Uri(s\"http://$host:$port/v2/keys\")\n  }\n\n  private val baseUri = kvUri.withPath(kvUri.path / \"constructr\" / clusterName)\n\n  private val nodesUri = baseUri.withPath(baseUri.path / \"nodes\")\n\n  override def getNodes() = {\n    def unmarshalNodes(entity: ResponseEntity) = {\n      def toNodes(s: String) = {\n        def jsonToNode(json: Json) = {\n          val init = nodesUri.path.toString.stripPrefix(kvUri.path.toString)\n          val key =\n            json.hcursor\n              .get[String](\"key\")\n              .fold(throw _, identity)\n              .stripPrefix(s\"$init/\")\n          val uri = new String(getUrlDecoder.decode(key), UTF_8)\n          AddressFromURIString(uri)\n        }\n        import cats.syntax.either._ // for Scala 2.11\n        parse(s)\n          .fold(throw _, identity)\n          .hcursor\n          .downField(\"node\")\n          .get[Set[Json]](\"nodes\")\n          .getOrElse(Set.empty)\n          .map(jsonToNode)\n      }\n      Unmarshal(entity).to[String].map(toNodes)\n    }\n    responseFor(Get(nodesUri)).flatMap {\n      case HttpResponse(OK, _, entity, _) =>\n        unmarshalNodes(entity)\n      case HttpResponse(NotFound, _, entity, _) =>\n        ignore(entity).map(_ => Set.empty)\n      case HttpResponse(other, _, entity, _) =>\n        ignore(entity).map(_ => throw UnexpectedStatusCode(nodesUri, other))\n    }\n  }\n\n  override def lock(self: Address, ttl: FiniteDuration) = {\n    val lockUri =\n      baseUri\n        .withPath(baseUri.path / \"lock\")\n        .withQuery(Uri.Query(\"value\" -> self.toString))\n    def readLock() = {\n      def unmarshalLockHolder(entity: ResponseEntity) = {\n        def toLockHolder(s: String) =\n          parse(s)\n            .fold(throw _, identity)\n            .hcursor\n            .downField(\"node\")\n            .get[String](\"value\")\n            .fold(throw _, identity)\n        Unmarshal(entity).to[String].map(toLockHolder)\n      }\n      responseFor(Get(lockUri)).flatMap {\n        case HttpResponse(OK, _, entity, _) =>\n          unmarshalLockHolder(entity).map(Some(_))\n        case HttpResponse(NotFound, _, entity, _) =>\n          ignore(entity).map(_ => None)\n        case HttpResponse(other, _, entity, _) =>\n          ignore(entity).map(_ => throw UnexpectedStatusCode(nodesUri, other))\n      }\n    }\n    def writeLock() = {\n      val uri =\n        lockUri.withQuery(\n          (\"prevExist\" -> \"false\") +: (\"ttl\" -> toSeconds(ttl)) +:\n          Uri.Query(lockUri.rawQueryString)\n        )\n      responseFor(Put(uri)).flatMap {\n        case HttpResponse(Created, _, entity, _) =>\n          ignore(entity).map(_ => true)\n        case HttpResponse(PreconditionFailed, _, entity, _) =>\n          ignore(entity).map(_ => false)\n        case HttpResponse(other, _, entity, _) =>\n          ignore(entity).map(_ => throw UnexpectedStatusCode(lockUri, other))\n      }\n    }\n    def updateLock(lockHolder: String) = {\n      val uri =\n        lockUri.withQuery(\n          (\"prevValue\" -> lockHolder) +: (\"ttl\" -> toSeconds(ttl)) +:\n          Uri.Query(lockUri.rawQueryString)\n        )\n      responseFor(Put(uri)).flatMap {\n        case HttpResponse(OK, _, entity, _) =>\n          ignore(entity).map(_ => true)\n        case HttpResponse(PreconditionFailed, _, entity, _) =>\n          ignore(entity).map(_ => false)\n        case HttpResponse(other, _, entity, _) =>\n          ignore(entity).map(_ => throw UnexpectedStatusCode(lockUri, other))\n      }\n    }\n    readLock().flatMap {\n      case Some(h) if h == self.toString => updateLock(h)\n      case Some(_)                       => Future.successful(false)\n      case None                          => writeLock()\n    }\n  }\n\n  override def addSelf(self: Address, ttl: FiniteDuration) =\n    addSelfOrRefresh(self, ttl)\n\n  override def refresh(self: Address, ttl: FiniteDuration) =\n    addSelfOrRefresh(self, ttl)\n\n  private def addSelfOrRefresh(self: Address, ttl: FiniteDuration) = {\n    val node  = getUrlEncoder.encodeToString(self.toString.getBytes(UTF_8))\n    val query = Uri.Query(\"ttl\" -> toSeconds(ttl), \"value\" -> self.toString)\n    val uri   = nodesUri.withPath(nodesUri.path / node).withQuery(query)\n    responseFor(Put(uri)).flatMap {\n      case HttpResponse(OK | Created, _, entity, _) =>\n        ignore(entity).map(_ => Done)\n      case HttpResponse(other, _, entity, _) =>\n        ignore(entity).map(_ => throw UnexpectedStatusCode(uri, other))\n    }\n  }\n\n  private def responseFor(request: HttpRequest) =\n    Http(system).singleRequest(request)\n\n  private def ignore(entity: ResponseEntity) =\n    entity.dataBytes.runWith(Sink.ignore)\n}\n"
  },
  {
    "path": "coordination-etcd/src/test/scala/de/heikoseeberger/constructr/coordination/etcd/EtcdCoordinationSpec.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr.coordination.etcd\n\nimport akka.Done\nimport akka.actor.{ ActorSystem, AddressFromURIString }\nimport akka.testkit.{ TestDuration, TestProbe }\nimport com.typesafe.config.ConfigFactory\nimport org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpec }\nimport scala.concurrent.duration.{ Duration, DurationInt, FiniteDuration }\nimport scala.concurrent.{ Await, Awaitable }\nimport scala.util.Random\n\nobject EtcdCoordinationSpec {\n\n  private val coordinationHost = {\n    val dockerHostPattern = \"\"\"tcp://(\\S+):\\d{1,5}\"\"\".r\n    sys.env\n      .get(\"DOCKER_HOST\")\n      .collect { case dockerHostPattern(address) => address }\n      .getOrElse(\"127.0.0.1\")\n  }\n}\n\nclass EtcdCoordinationSpec extends WordSpec with Matchers with BeforeAndAfterAll {\n  import EtcdCoordinationSpec._\n\n  private implicit val system = {\n    val config =\n      ConfigFactory\n        .parseString(s\"constructr.coordination.host = $coordinationHost\")\n        .withFallback(ConfigFactory.load())\n    ActorSystem(\"default\", config)\n  }\n\n  private val address  = AddressFromURIString(\"akka.tcp://default@a:2552\")\n  private val address2 = AddressFromURIString(\"akka.tcp://default@b:2552\")\n\n  \"EtcdCoordination\" should {\n    \"correctly interact with etcd\" in {\n      val coordination = new EtcdCoordination(randomString(), system)\n\n      resultOf(coordination.getNodes()) shouldBe 'empty\n\n      resultOf(coordination.lock(address, 10.seconds.dilated)) shouldBe true\n      resultOf(coordination.lock(address, 10.seconds.dilated)) shouldBe true\n      resultOf(coordination.lock(address2, 10.seconds.dilated)) shouldBe false\n\n      resultOf(coordination.addSelf(address, 10.seconds.dilated)) shouldBe Done\n      resultOf(coordination.getNodes()) shouldBe Set(address)\n\n      resultOf(coordination.refresh(address, 1.second.dilated)) shouldBe Done\n      resultOf(coordination.getNodes()) shouldBe Set(address)\n\n      val probe = TestProbe()\n      probe.within(5.seconds.dilated) { // 2 seconds should be enough, but who knows hows ...\n        probe.awaitAssert {\n          resultOf(coordination.getNodes()) shouldBe 'empty\n        }\n      }\n    }\n  }\n\n  override protected def afterAll() = {\n    Await.ready(system.terminate(), Duration.Inf)\n    super.afterAll()\n  }\n\n  private def resultOf[A](awaitable: Awaitable[A], max: FiniteDuration = 3.seconds.dilated) =\n    Await.result(awaitable, max)\n\n  private def randomString() = math.abs(Random.nextInt).toString\n}\n"
  },
  {
    "path": "core/src/main/resources/reference.conf",
    "content": "constructr {\n  coordination-timeout    = 3 seconds  // Maximum response time for coordination service (e.g. etcd)\n  join-timeout            = 15 seconds // Might depend on cluster size and network properties\n  abort-on-join-timeout   = false      // Abort the attempt to join if true; otherwise restart the process from scratch\n  max-nr-of-seed-nodes    = 0          // Any nonpositive value means Int.MaxValue\n  nr-of-retries           = 2          // Nr. of tries are nr. of retries + 1\n  refresh-interval        = 30 seconds // TTL is refresh-interval * ttl-factor\n  retry-delay             = 3 seconds  // Give coordination service (e.g. etcd) some delay before retrying\n  ttl-factor              = 2.0        // Must be greater or equal 1 + ((coordination-timeout * (1 + nr-of-retries) + retry-delay * nr-of-retries)/ refresh-interval)!\n  ignore-refresh-failures = false      // Ignore failures once machine is already in \"Refreshing\" state. It prevents from FSM being terminated due to exhausted number of retries.\n}\n"
  },
  {
    "path": "core/src/main/scala/de/heikoseeberger/constructr/Constructr.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.actor.{ Actor, ActorLogging, ActorRef, Props, SupervisorStrategy, Terminated }\nimport akka.cluster.{ Cluster, Member }\nimport akka.cluster.ClusterEvent.{ InitialStateAsEvents, MemberExited, MemberLeft, MemberRemoved }\nimport akka.cluster.MemberStatus.Up\nimport de.heikoseeberger.constructr.coordination.Coordination\nimport scala.concurrent.duration.{ FiniteDuration, NANOSECONDS }\n\nobject Constructr {\n\n  final val Name = \"constructr\"\n\n  def props: Props =\n    Props(new Constructr)\n}\n\nfinal class Constructr private extends Actor with ActorLogging {\n\n  override val supervisorStrategy = SupervisorStrategy.stoppingStrategy\n\n  private val cluster = Cluster(context.system)\n\n  if (cluster.settings.SeedNodes.isEmpty) {\n    log.info(\"Creating constructr-machine, because no seed-nodes defined\")\n    cluster.subscribe(self,\n                      InitialStateAsEvents,\n                      classOf[MemberLeft],\n                      classOf[MemberExited],\n                      classOf[MemberRemoved])\n    context.become(active(context.watch(createConstructrMachine())))\n  } else {\n    log.info(\"Stopping self, because seed-nodes defined\")\n    context.stop(self)\n  }\n\n  override def receive = Actor.emptyBehavior\n\n  private def active(machine: ActorRef): Receive = {\n    case Terminated(`machine`) =>\n      val selfAddress = cluster.selfAddress\n      def isSelfAndUp(member: Member) =\n        member.address == selfAddress && member.status == Up\n      if (cluster.state.members.exists(isSelfAndUp)) {\n        log.error(\"Leaving, because constructr-machine terminated!\")\n        cluster.leave(selfAddress)\n      } else {\n        log.error(\"Terminating system, because constructr-machine terminated!\")\n        context.system.terminate()\n      }\n\n    case MemberRemoved(member, _) if member.address == cluster.selfAddress =>\n      log.error(\"Terminating system, because member has been removed!\")\n      context.system.terminate()\n  }\n\n  private def createConstructrMachine() = {\n    val config = context.system.settings.config\n    def getDuration(key: String) =\n      FiniteDuration(config.getDuration(key).toNanos, NANOSECONDS)\n\n    val coordinationTimeout   = getDuration(\"constructr.coordination-timeout\")\n    val nrOfRetries           = config.getInt(\"constructr.nr-of-retries\")\n    val retryDelay            = getDuration(\"constructr.retry-delay\")\n    val refreshInterval       = getDuration(\"constructr.refresh-interval\")\n    val ttlFactor             = config.getDouble(\"constructr.ttl-factor\")\n    val maxNrOfSeedNodes      = config.getInt(\"constructr.max-nr-of-seed-nodes\")\n    val joinTimeout           = getDuration(\"constructr.join-timeout\")\n    val abortOnJoinTimeout    = config.getBoolean(\"constructr.abort-on-join-timeout\")\n    val ignoreRefreshFailures = config.getBoolean(\"constructr.ignore-refresh-failures\")\n\n    context.actorOf(\n      ConstructrMachine.props(\n        cluster.selfAddress,\n        Coordination(context.system.name, context.system),\n        coordinationTimeout,\n        nrOfRetries,\n        retryDelay,\n        refreshInterval,\n        ttlFactor,\n        if (maxNrOfSeedNodes <= 0) Int.MaxValue else maxNrOfSeedNodes,\n        joinTimeout,\n        abortOnJoinTimeout,\n        ignoreRefreshFailures\n      ),\n      ConstructrMachine.Name\n    )\n  }\n}\n"
  },
  {
    "path": "core/src/main/scala/de/heikoseeberger/constructr/ConstructrExtension.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.actor.{ ExtendedActorSystem, Extension, ExtensionKey }\n\nobject ConstructrExtension extends ExtensionKey[ConstructrExtension]\n\nfinal class ConstructrExtension private (system: ExtendedActorSystem) extends Extension {\n  system.systemActorOf(Constructr.props, Constructr.Name)\n}\n"
  },
  {
    "path": "core/src/main/scala/de/heikoseeberger/constructr/ConstructrMachine.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.Done\nimport akka.actor.{ Address, FSM, Props, Status }\nimport akka.cluster.Cluster\nimport akka.cluster.ClusterEvent.{ InitialStateAsEvents, MemberJoined, MemberUp }\nimport akka.pattern.pipe\nimport akka.stream.ActorMaterializer\nimport de.heikoseeberger.constructr.coordination.Coordination\n\nimport scala.concurrent.duration.{ Duration, FiniteDuration }\n\nobject ConstructrMachine {\n\n  implicit class DurationOps(val duration: Duration) extends AnyVal {\n\n    def toFinite: FiniteDuration =\n      duration match {\n        case Duration(n, unit) => Duration(n, unit)\n        case _                 => throw new IllegalStateException(\"Infinite duration!\")\n      }\n  }\n\n  sealed trait State\n  final object State {\n    case object BeforeGettingNodes extends State\n    case object GettingNodes       extends State\n    case object Locking            extends State\n    case object Joining            extends State\n    case object AddingSelf         extends State\n    case object RefreshScheduled   extends State\n    case object Refreshing         extends State\n    case object RetryScheduled     extends State\n  }\n\n  final case class Data(nodes: Set[Address], retryState: State, nrOfRetriesLeft: Int)\n\n  final case class StateTimeoutException(state: State)\n      extends RuntimeException(s\"State timeout triggered in state $state!\")\n\n  final val Name = \"constructr-machine\"\n\n  def props(\n      selfNode: Address,\n      coordination: Coordination,\n      coordinationTimeout: FiniteDuration,\n      coordinationRetries: Int,\n      retryDelay: FiniteDuration,\n      refreshInterval: FiniteDuration,\n      ttlFactor: Double,\n      maxNrOfSeedNodes: Int,\n      joinTimeout: FiniteDuration,\n      abortOnJoinTimeout: Boolean,\n      ignoreRefreshFailures: Boolean\n  ): Props =\n    Props(\n      new ConstructrMachine(\n        selfNode,\n        coordination,\n        coordinationTimeout,\n        coordinationRetries,\n        retryDelay,\n        refreshInterval,\n        ttlFactor,\n        maxNrOfSeedNodes,\n        joinTimeout,\n        abortOnJoinTimeout,\n        ignoreRefreshFailures\n      )\n    )\n}\n\nfinal class ConstructrMachine(\n    val selfNode: Address,\n    coordination: Coordination,\n    coordinationTimeout: FiniteDuration,\n    nrOfRetries: Int,\n    retryDelay: FiniteDuration,\n    refreshInterval: FiniteDuration,\n    ttlFactor: Double,\n    maxNrOfSeedNodes: Int,\n    joinTimeout: FiniteDuration,\n    abortOnJoinTimeout: Boolean,\n    ignoreRefreshFailures: Boolean\n) extends FSM[ConstructrMachine.State, ConstructrMachine.Data] {\n  import ConstructrMachine._\n  import context.dispatcher\n\n  require(maxNrOfSeedNodes > 0,\n          s\"max-nr-of-seed-nodes must be positive, but was $maxNrOfSeedNodes!\")\n  require(\n    ttlFactor >= minTtlFactor,\n    s\"ttl-factor must be greater or equal 1 + ((coordination-timeout * (1 + nr-of-retries) + retry-delay * nr-of-retries)/ refresh-interval), i.e. $minTtlFactor, but was $ttlFactor!\"\n  )\n\n  private val cluster = Cluster(context.system)\n\n  startWith(State.GettingNodes, Data(Set.empty, State.GettingNodes, nrOfRetries))\n\n  // Before getting nodes\n\n  when(State.BeforeGettingNodes, retryDelay) {\n    case Event(StateTimeout, _) =>\n      goto(State.GettingNodes).using(Data(Set.empty, State.GettingNodes, nrOfRetries))\n  }\n\n  // Getting nodes\n\n  onTransition {\n    case _ -> State.GettingNodes =>\n      log.debug(\"Transitioning to GettingNodes\")\n      coordination.getNodes().map { nodes =>\n        if (nodes.contains(selfNode))\n          log.warning(\n            s\"Selfnode received in list of nodes $nodes. Will filter to prevent forming an island.\"\n          )\n\n        nodes.filterNot(_ == selfNode)\n      } pipeTo self\n  }\n\n  when(State.GettingNodes, coordinationTimeout) {\n    case Event(nodes: Set[Address] @unchecked, _) if nodes.isEmpty =>\n      log.debug(\"Received empty nodes, going to Locking\")\n      goto(State.Locking)\n        .using(stateData.copy(nrOfRetriesLeft = nrOfRetries))\n\n    case Event(nodes: Set[Address] @unchecked, _) =>\n      log.debug(s\"Received nodes $nodes, going to Joining\")\n      goto(State.Joining)\n        .using(stateData.copy(nodes = nodes, nrOfRetriesLeft = nrOfRetries))\n\n    case Event(Status.Failure(cause), _) =>\n      log.warning(s\"Failure in $stateName, going to GettingNodes: $cause\")\n      retry(State.GettingNodes)\n\n    case Event(StateTimeout, _) =>\n      log.warning(s\"Timeout in $stateName, going to GettingNodes\")\n      retry(State.GettingNodes)\n  }\n\n  // Locking\n\n  onTransition {\n    case _ -> State.Locking =>\n      log.debug(\"Transitioning to Locking\")\n      val ttl = (2 * maxCoordinationTimeout + joinTimeout) * ttlFactor // Keep lock until self added\n      coordination.lock(selfNode, ttl.toFinite).pipeTo(self)\n  }\n\n  when(State.Locking, coordinationTimeout) {\n    case Event(true, _) =>\n      log.debug(\"Successfully locked, going to Joining\")\n      goto(State.Joining).using(\n        stateData.copy(nodes = Set(selfNode), nrOfRetriesLeft = nrOfRetries)\n      )\n\n    case Event(false, _) =>\n      log.warning(\"Couldn't acquire lock, going to GettingNodes\")\n      goto(State.BeforeGettingNodes)\n\n    case Event(Status.Failure(cause), _) =>\n      log.warning(s\"Failure in $stateName, going to Locking: $cause\")\n      retry(State.Locking)\n\n    case Event(StateTimeout, _) =>\n      log.warning(s\"Timeout in $stateName, going to Locking\")\n      retry(State.Locking)\n  }\n\n  // Joining\n\n  onTransition {\n    case _ -> State.Joining =>\n      log.debug(\"Transitioning to Joining\")\n      cluster.joinSeedNodes(seedNodes(nextStateData.nodes)) // An existing seed node process would be stopped\n      Cluster(context.system).subscribe(self,\n                                        InitialStateAsEvents,\n                                        classOf[MemberJoined],\n                                        classOf[MemberUp])\n\n  }\n\n  when(State.Joining, joinTimeout) {\n    case Event(MemberJoined(member), _) if member.address == selfNode =>\n      goto(State.AddingSelf)\n\n    case Event(MemberUp(member), _) if member.address == selfNode =>\n      goto(State.AddingSelf)\n\n    case Event(StateTimeout, _) =>\n      if (abortOnJoinTimeout)\n        stop(FSM.Failure(\"Timeout in Joining!\"))\n      else\n        goto(State.GettingNodes).using(Data(Set.empty, State.GettingNodes, nrOfRetries))\n  }\n\n  onTransition {\n    case State.Joining -> _ =>\n      log.debug(\"Transitioning out of Joining\")\n      cluster.unsubscribe(self)\n  }\n\n  private def seedNodes(nodes: Set[Address]) =\n    nodes.take(maxNrOfSeedNodes).toVector\n\n  // AddingSelf\n\n  onTransition {\n    case _ -> State.AddingSelf =>\n      log.debug(\"Transitioning to AddingSelf\")\n      coordination\n        .addSelf(selfNode, addingSelfOrRefreshingTtl.toFinite)\n        .pipeTo(self)\n  }\n\n  when(State.AddingSelf, coordinationTimeout) {\n    case Event(Done, data) =>\n      log.debug(\"Successfully added self, going to RefreshScheduled\")\n      goto(State.RefreshScheduled)\n        .using(data.copy(nrOfRetriesLeft = nrOfRetries))\n\n    case Event(Status.Failure(cause), _) =>\n      log.warning(s\"Failure in $stateName, going to AddingSelf: $cause\")\n      retry(State.AddingSelf)\n\n    case Event(StateTimeout, _) =>\n      log.warning(s\"Timeout in $stateName, going to AddingSelf\")\n      retry(State.AddingSelf)\n  }\n\n  // RefreshScheduled\n\n  onTransition {\n    case _ -> State.RefreshScheduled =>\n      log.debug(\"Transitioning to RefreshScheduled\")\n  }\n\n  when(State.RefreshScheduled, refreshInterval) {\n    case Event(StateTimeout, _) =>\n      log.debug(s\"Waited for $refreshInterval, going to Refreshing\")\n      goto(State.Refreshing)\n  }\n\n  // Refreshing\n\n  onTransition {\n    case _ -> State.Refreshing =>\n      log.debug(s\"Transitioning to Refreshing\")\n      coordination\n        .refresh(selfNode, addingSelfOrRefreshingTtl.toFinite)\n        .pipeTo(self)\n  }\n\n  when(State.Refreshing, coordinationTimeout) {\n    case Event(Done, _) =>\n      log.debug(\"Successfully refreshed, going to RefreshScheduled\")\n      goto(State.RefreshScheduled)\n        .using(stateData.copy(nrOfRetriesLeft = nrOfRetries))\n\n    case Event(Status.Failure(cause), _) =>\n      log.warning(s\"Failure in $stateName, going to Refreshing: $cause\")\n      retryRefreshing()\n\n    case Event(StateTimeout, _) =>\n      log.warning(s\"Timeout in $stateName, going to Refreshing\")\n      retryRefreshing()\n  }\n\n  // RetryScheduled\n\n  onTransition {\n    case state -> State.RetryScheduled =>\n      log.debug(s\"Transitioning from $state to RetryScheduled\")\n  }\n\n  when(State.RetryScheduled, retryDelay) {\n    case Event(StateTimeout, Data(_, retryState, _)) =>\n      log.debug(s\"Waited for $retryDelay, going to $retryState\")\n      goto(retryState)\n  }\n\n  // Unhandled events\n\n  whenUnhandled {\n    case Event(MemberJoined(member), _) if member.address == selfNode && isPreJoining =>\n      goto(State.AddingSelf).using(stateData.copy(nrOfRetriesLeft = nrOfRetries))\n    case Event(MemberUp(member), _) if member.address == selfNode && isPreJoining =>\n      goto(State.AddingSelf).using(stateData.copy(nrOfRetriesLeft = nrOfRetries))\n    // Unsubscribe might be late\n    case Event(MemberJoined(_) | MemberUp(_), _) => stay()\n  }\n\n  // Initialization\n\n  initialize()\n\n  // Helpers\n\n  private def retry(retryState: ConstructrMachine.State) =\n    if (stateData.nrOfRetriesLeft <= 0)\n      stop(FSM.Failure(s\"Number of retries exhausted in $stateName!\"))\n    else\n      goto(State.RetryScheduled).using(\n        stateData.copy(retryState = retryState, nrOfRetriesLeft = stateData.nrOfRetriesLeft - 1)\n      )\n\n  private def maxCoordinationTimeout =\n    coordinationTimeout * (1 + nrOfRetries) + retryDelay * nrOfRetries\n\n  private def minTtlFactor = 1 + maxCoordinationTimeout / refreshInterval\n\n  private def addingSelfOrRefreshingTtl = refreshInterval * ttlFactor\n\n  private def retryRefreshing() =\n    if (ignoreRefreshFailures)\n      goto(State.RetryScheduled).using(\n        stateData.copy(retryState = State.Refreshing, nrOfRetriesLeft = nrOfRetries)\n      )\n    else\n      retry(State.Refreshing)\n\n  private def isPreJoining: Boolean =\n    stateName match {\n      case State.BeforeGettingNodes | State.GettingNodes | State.Locking => true\n      case _                                                             => false\n    }\n}\n"
  },
  {
    "path": "core/src/main/scala/de/heikoseeberger/constructr/package.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger\n\npackage object constructr {\n\n  type Traversable[+A] = scala.collection.immutable.Traversable[A]\n  type Iterable[+A]    = scala.collection.immutable.Iterable[A]\n  type Seq[+A]         = scala.collection.immutable.Seq[A]\n  type IndexedSeq[+A]  = scala.collection.immutable.IndexedSeq[A]\n}\n"
  },
  {
    "path": "core/src/multi-jvm/resources/application.conf",
    "content": "akka.actor.provider = akka.cluster.ClusterActorRefProvider\n\n"
  },
  {
    "path": "core/src/multi-jvm/resources/log4j2.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<Configuration>\n    <Appenders>\n        <Console name=\"STDOUT\">\n            <PatternLayout>\n                <pattern>%date{HH:mm:ss} %-5level %logger{0} [%X{akkaSource}] - %msg%n</pattern>\n            </PatternLayout>\n        </Console>\n        <File name=\"FILE\" fileName=\"constructr.log\" append=\"false\">\n            <PatternLayout>\n                <pattern>%date{HH:mm:ss} %-5level %logger{0} [%X{akkaSource}] - %msg%n</pattern>\n            </PatternLayout>\n        </File>\n    </Appenders>\n\n    <Loggers>\n        <Logger name=\"de.heikoseeberger.constructr\" level=\"debug\" additivity=\"false\">\n            <AppenderRef ref=\"STDOUT\"/>\n            <AppenderRef ref=\"FILE\"/>\n        </Logger>\n        <Logger name=\"Remoting\" level=\"off\" additivity=\"false\">\n        </Logger>\n        <Logger name=\"akka.remote.EndpointWriter\" level=\"off\" additivity=\"false\">\n        </Logger>\n        <Logger name=\"akka.cluster.ClusterHeartbeatSender\" level=\"off\" additivity=\"false\">\n        </Logger>\n        <Root level=\"warn\">\n            <AppenderRef ref=\"STDOUT\"/>\n            <AppenderRef ref=\"FILE\"/>\n        </Root>\n    </Loggers>\n</Configuration>\n"
  },
  {
    "path": "core/src/multi-jvm/scala/de/heikoseeberger/constructr/MultiNodeConstructrSpec.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.actor.ActorDSL.{ actor, Act }\nimport akka.actor.Address\nimport akka.cluster.{ Cluster, ClusterEvent }\nimport akka.http.scaladsl.Http\nimport akka.http.scaladsl.client.RequestBuilding\nimport akka.http.scaladsl.model.StatusCodes.{ NotFound, OK }\nimport akka.http.scaladsl.unmarshalling.Unmarshal\nimport akka.pattern.ask\nimport akka.remote.testkit.{ MultiNodeConfig, MultiNodeSpec }\nimport akka.stream.ActorMaterializer\nimport akka.testkit.TestDuration\nimport akka.util.Timeout\nimport com.typesafe.config.ConfigFactory\nimport org.scalatest.{ BeforeAndAfterAll, FreeSpecLike, Matchers }\nimport scala.concurrent.Await\nimport scala.concurrent.duration.DurationInt\n\nobject ConstructrMultiNodeConfig {\n  val coordinationHost = {\n    val dockerHostPattern = \"\"\"tcp://(\\S+):\\d{1,5}\"\"\".r\n    sys.env\n      .get(\"DOCKER_HOST\")\n      .collect { case dockerHostPattern(address) => address }\n      .getOrElse(\"127.0.0.1\")\n  }\n}\n\nclass ConstructrMultiNodeConfig(coordinationPort: Int) extends MultiNodeConfig {\n  import ConstructrMultiNodeConfig._\n\n  commonConfig(ConfigFactory.load())\n  for (n <- 1.to(5)) {\n    val port = 2550 + n\n    nodeConfig(role(port.toString))(\n      ConfigFactory.parseString(\n        s\"\"\"|akka.actor.provider            = akka.cluster.ClusterActorRefProvider\n          |akka.remote.netty.tcp.hostname = \"127.0.0.1\"\n          |akka.remote.netty.tcp.port     = $port\n          |constructr.coordination.host   = $coordinationHost\n          |constructr.coordination.port   = $coordinationPort\n          |\"\"\".stripMargin\n      )\n    )\n  }\n}\n\nabstract class MultiNodeConstructrSpec(\n    coordinationPort: Int,\n    delete: String,\n    get: String,\n    toNodes: String => Set[Address]\n) extends MultiNodeSpec(new ConstructrMultiNodeConfig(coordinationPort))\n    with FreeSpecLike\n    with Matchers\n    with BeforeAndAfterAll {\n  import ConstructrMultiNodeConfig._\n  import RequestBuilding._\n  import system.dispatcher\n\n  implicit val mat = ActorMaterializer()\n\n  \"Constructr should manage an Akka cluster\" in {\n    runOn(roles.head) {\n      within(20.seconds.dilated) {\n        awaitAssert {\n          val coordinationStatus =\n            Await.result(\n              Http()\n                .singleRequest(\n                  Delete(s\"http://$coordinationHost:$coordinationPort$delete\")\n                )\n                .map(_.status),\n              5.seconds.dilated // As this is the first request fired via `singleRequest`, creating the pool takes some time (probably)\n            )\n          coordinationStatus should (be(OK) or be(NotFound))\n        }\n      }\n    }\n\n    enterBarrier(\"coordination-started\")\n\n    ConstructrExtension(system)\n    val listener = actor(new Act {\n      import ClusterEvent._\n      var isMember = false\n      Cluster(context.system).subscribe(self,\n                                        InitialStateAsEvents,\n                                        classOf[MemberJoined],\n                                        classOf[MemberUp])\n      become {\n        case \"isMember\" => sender() ! isMember\n\n        case MemberJoined(member) if member.address == Cluster(context.system).selfAddress =>\n          isMember = true\n\n        case MemberUp(member) if member.address == Cluster(context.system).selfAddress =>\n          isMember = true\n      }\n    })\n    within(20.seconds.dilated) {\n      awaitAssert {\n        implicit val timeout = Timeout(1.second.dilated)\n        val isMember         = Await.result((listener ? \"isMember\").mapTo[Boolean], 1.second.dilated)\n        isMember shouldBe true\n      }\n    }\n\n    enterBarrier(\"cluster-formed\")\n\n    within(5.seconds.dilated) {\n      awaitAssert {\n        val constructrNodes =\n          Await.result(\n            Http()\n              .singleRequest(\n                Get(s\"http://$coordinationHost:$coordinationPort$get\")\n              )\n              .flatMap(Unmarshal(_).to[String].map(toNodes)),\n            1.second.dilated\n          )\n        val ports = constructrNodes.flatMap(_.port)\n        ports shouldBe roles.to[Set].map(_.name.toInt)\n      }\n    }\n\n    enterBarrier(\"done\")\n  }\n\n  override def initialParticipants = roles.size\n\n  override protected def beforeAll() = {\n    super.beforeAll()\n    multiNodeSpecBeforeAll()\n  }\n\n  override protected def afterAll() = {\n    multiNodeSpecAfterAll()\n    super.afterAll()\n  }\n}\n"
  },
  {
    "path": "core/src/multi-jvm/scala/de/heikoseeberger/constructr/MultiNodeEtcdConstructrSpec.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.actor.{ Address, AddressFromURIString }\nimport io.circe.Json\nimport io.circe.parser.parse\nimport java.util.Base64\n\nclass MultiNodeEtcdConstructrSpecMultiJvmNode1 extends MultiNodeEtcdConstructrSpec\nclass MultiNodeEtcdConstructrSpecMultiJvmNode2 extends MultiNodeEtcdConstructrSpec\nclass MultiNodeEtcdConstructrSpecMultiJvmNode3 extends MultiNodeEtcdConstructrSpec\nclass MultiNodeEtcdConstructrSpecMultiJvmNode4 extends MultiNodeEtcdConstructrSpec\nclass MultiNodeEtcdConstructrSpecMultiJvmNode5 extends MultiNodeEtcdConstructrSpec\n\nobject MultiNodeEtcdConstructrSpec {\n  def toNodes(s: String): Set[Address] = {\n    def jsonToNode(json: Json) = {\n      val key =\n        json.hcursor\n          .get[String](\"key\")\n          .fold(throw _, identity)\n          .stripPrefix(\"/constructr/MultiNodeConstructrSpec/nodes/\")\n      AddressFromURIString(new String(Base64.getUrlDecoder.decode(key)))\n    }\n    import cats.syntax.either._ // for Scala 2.11\n    parse(s)\n      .fold(throw _, identity)\n      .hcursor\n      .downField(\"node\")\n      .get[Set[Json]](\"nodes\")\n      .getOrElse(Set.empty)\n      .map(jsonToNode)\n  }\n}\n\nabstract class MultiNodeEtcdConstructrSpec\n    extends MultiNodeConstructrSpec(\n      2379,\n      \"/v2/keys/constructr?recursive=true\",\n      \"/v2/keys/constructr/MultiNodeConstructrSpec/nodes\",\n      MultiNodeEtcdConstructrSpec.toNodes\n    )\n"
  },
  {
    "path": "core/src/test/resources/application.conf",
    "content": "akka.actor.provider = akka.cluster.ClusterActorRefProvider\n\n"
  },
  {
    "path": "core/src/test/scala/de/heikoseeberger/constructr/ConstructrExtensionSpec.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport java.util.UUID\n\nimport akka.actor.ActorSystem\nimport akka.cluster.{ Cluster, MemberStatus }\nimport com.typesafe.config.ConfigFactory\nimport de.heikoseeberger.constructr.testutil.CoordinationInfo\nimport org.scalatest.concurrent.Eventually\nimport org.scalatest.mockito.MockitoSugar\nimport org.scalatest.time._\nimport org.scalatest.{ BeforeAndAfterEach, Matchers, WordSpec }\n\nimport scala.concurrent.duration._\nimport scala.concurrent.{ Await, ExecutionContext, Future }\n\nclass ConstructrExtensionSpec\n    extends WordSpec\n    with Matchers\n    with MockitoSugar\n    with BeforeAndAfterEach\n    with Eventually {\n\n  import ConstructrExtensionSpec._\n\n  private[this] var clusterNodes = Seq.empty[ActorSystem]\n\n  override protected def afterEach(): Unit =\n    dispose(clusterNodes)\n\n  \"Cluster members managed by ConstructR\" should {\n    // Happy path\n    \"successfully join the cluster under normal circumstances\" in {\n      val clusterName = generateClusterName()\n      clusterNodes = 0.until(5).map(i => createClusterNode(clusterName, 15000 + i))\n      eventuallyUp(clusterNodes, 10.seconds)\n    }\n\n    /*\n     * An initial set of nodes joins the cluster and crashes, thus leaving the corresponding seed entries at\n     * the backend. A second set of nodes attempts to join the cluster prior to the expiration of the previous\n     * seed entries, thus initiating join attempts to seed nodes that are no longer alive. These attempts will\n     * continue to fail, until the original seed entries expire, and one of the new nodes manages to register\n     * itself as the new seed and formulate a cluster. After that the rest of the nodes will eventually join\n     * as well.\n     */\n    \"eventually join the cluster if initial seeds crash\" in {\n      val clusterName = generateClusterName()\n      val basePort    = 15005\n      clusterNodes = 0.until(1).map(i => createClusterNode(clusterName, basePort + i))\n      eventuallyUp(clusterNodes, 10.seconds)\n      dispose(clusterNodes)\n      clusterNodes = 1.until(5).map(i => createClusterNode(clusterName, basePort + i))\n\n      Thread.sleep(20.seconds.toMillis)\n\n      for (clusterNode <- clusterNodes) {\n        val clusterExtension = Cluster(clusterNode)\n        assert(clusterExtension.selfMember.status != MemberStatus.Up,\n               s\"node ${clusterExtension.selfAddress} is up\")\n      }\n\n      eventuallyUp(clusterNodes, 40.seconds)\n    }\n\n    /*\n     * An initial set of nodes joins the cluster and crashes, thus leaving the corresponding seed entries at\n     * the backend. A second set of nodes attempts to join the cluster prior to the expiration of the previous\n     * seed entries, thus initiating join attempts to seed nodes that are no longer alive. These attempts will\n     * continue to fail for a while, until the original set of nodes is restarted, and successfully formulates\n     * a cluster. After that the rest of the nodes will eventually join as well.\n     */\n    \"correctly join initial seeds if they crash but recover in time\" in {\n      val clusterName = generateClusterName()\n      val basePort    = 15010\n      clusterNodes = 0.until(1).map(i => createClusterNode(clusterName, basePort + i))\n      eventuallyUp(clusterNodes, 10.seconds)\n      dispose(clusterNodes)\n      clusterNodes = 1.until(5).map(i => createClusterNode(clusterName, basePort + i))\n\n      Thread.sleep(10.seconds.toMillis)\n\n      for (clusterNode <- clusterNodes) {\n        val clusterExtension = Cluster(clusterNode)\n        assert(clusterExtension.selfMember.status != MemberStatus.Up,\n               s\"node ${clusterExtension.selfAddress} is up\")\n      }\n\n      clusterNodes = createClusterNode(clusterName, basePort) +: clusterNodes\n      eventuallyUp(clusterNodes, 10.seconds)\n    }\n  }\n\n  private def eventuallyUp(cluster: scala.Seq[ActorSystem], within: FiniteDuration): Unit =\n    eventually(timeout(Span(within.toSeconds, Seconds)), interval(Span(2, Seconds))) {\n      for (clusterNode <- cluster) {\n        val clusterExtension = Cluster(clusterNode)\n        assert(clusterExtension.selfMember.status == MemberStatus.Up,\n               s\"node ${clusterExtension.selfAddress} is not up\")\n        assert(clusterExtension.state.members.size == cluster.size)\n      }\n    }\n}\n\nobject ConstructrExtensionSpec {\n\n  val ClusterNameBase: String = \"ConstructrExtensionSpecCluster\"\n\n  def generateClusterName(): String = s\"$ClusterNameBase-${UUID.randomUUID()}\"\n\n  def createClusterNode(name: String, port: Int): ActorSystem = {\n    val config = ConfigFactory.parseString(s\"\"\"\n        | akka {\n        |   actor.provider = akka.cluster.ClusterActorRefProvider\n        |   cluster.jmx.multi-mbeans-in-same-jvm = on\n        |\n        |   remote {\n        |     netty.tcp {\n        |       hostname = \"127.0.0.1\"\n        |       port = $port\n        |     }\n        |   }\n        | }\n        |\n        | constructr {\n        |   coordination {\n        |     host = \"${CoordinationInfo.host}\"\n        |     port = ${CoordinationInfo.port}\n        |   }\n        |\n        |   coordination-timeout = 2 seconds\n        |   join-timeout = 3 seconds\n        |   abort-on-join-timeout = false\n        |   nr-of-retries = 1\n        |   retry-delay = 2 seconds\n        |   refresh-interval = 6 seconds\n        | }\n      \"\"\".stripMargin)\n    val system = ActorSystem(name, config)\n    ConstructrExtension(system)\n    system\n  }\n\n  def dispose(clusterNodes: scala.Seq[ActorSystem]): Unit =\n    if (clusterNodes.nonEmpty) {\n      implicit val executor = ExecutionContext.Implicits.global\n      Await.result(Future.traverse(clusterNodes)(_.terminate()), 20.seconds)\n    }\n}\n"
  },
  {
    "path": "core/src/test/scala/de/heikoseeberger/constructr/ConstructrMachineSpec.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr\n\nimport akka.Done\nimport akka.actor.{ ActorSystem, Address, FSM, Props }\nimport akka.cluster.Cluster\nimport akka.pattern.{ after => delayed }\nimport akka.stream.ActorMaterializer\nimport akka.testkit.{ TestDuration, TestProbe }\nimport de.heikoseeberger.constructr.coordination.Coordination\nimport org.mockito.Mockito\nimport org.scalatest.{ BeforeAndAfterAll, Matchers, WordSpec }\nimport scala.concurrent.duration.{ Duration, DurationInt }\nimport scala.concurrent.{ Await, Future }\n\nfinal class ConstructrMachineSpec extends WordSpec with Matchers with BeforeAndAfterAll {\n  import ConstructrMachine._\n  import Mockito._\n\n  private implicit val system = ActorSystem()\n  private implicit val mat    = ActorMaterializer()\n  import system.dispatcher\n\n  private val address = Cluster(system).selfAddress\n\n  \"ConstructrMachine\" should {\n    \"retry the given number of retries and then fail\" in {\n      val coordination = mock(classOf[Coordination])\n      when(coordination.getNodes()).thenReturn(\n        // delay first getNodes call for a bit, so as not to transition out of GettingNodes state too fast\n        delayed(50.millis.dilated, system.scheduler)(boom()),\n        delayed(1.hour.dilated, system.scheduler)(noNodes())\n      )\n\n      val monitor = TestProbe()\n      val machine = system.actorOf(\n        Props(\n          new ConstructrMachine(\n            selfNode = address,\n            coordination = coordination,\n            coordinationTimeout = 100.millis.dilated,\n            nrOfRetries = 1,\n            retryDelay = 100.millis.dilated,\n            refreshInterval = 1.second.dilated,\n            ttlFactor = 1.5,\n            maxNrOfSeedNodes = 3,\n            joinTimeout = 100.millis.dilated,\n            abortOnJoinTimeout = false,\n            ignoreRefreshFailures = false\n          )\n        )\n      )\n      machine ! FSM.SubscribeTransitionCallBack(monitor.ref)\n      monitor.watch(machine)\n\n      monitor.expectMsgPF(hint = \"Current state GettingNodes\") {\n        case FSM.CurrentState(_, State.GettingNodes) => ()\n      }\n      monitor.expectMsgPF(hint = \"GettingNodes -> RetryScheduled\") {\n        case FSM.Transition(_, State.GettingNodes, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> GettingNodes\") {\n        case FSM.Transition(_, State.RetryScheduled, State.GettingNodes) => ()\n      }\n\n      monitor.expectTerminated(machine)\n    }\n\n    \"correctly work down the happy path (including retries)\" in {\n      val coordination = mock(classOf[Coordination])\n      when(coordination.getNodes()).thenReturn(\n        delayed(1.hour.dilated, system.scheduler)(noNodes()),\n        boom(),\n        noNodes(),\n        noNodes()\n      )\n      when(coordination.lock(address, 1650.millis.dilated)).thenReturn(\n        delayed(1.hour.dilated, system.scheduler)(boom()),\n        boom(),\n        Future.successful(false),\n        Future.successful(true)\n      )\n      when(coordination.addSelf(address, 1500.millis.dilated)).thenReturn(\n        delayed(1.hour.dilated, system.scheduler)(boom()),\n        boom(),\n        Future.successful(Done)\n      )\n      when(coordination.refresh(address, 1500.millis.dilated)).thenReturn(\n        delayed(1.hour.dilated, system.scheduler)(boom()),\n        boom(),\n        Future.successful(Done)\n      )\n\n      val monitor = TestProbe()\n      val machine = system.actorOf(\n        Props(\n          new ConstructrMachine(\n            selfNode = address,\n            coordination = coordination,\n            coordinationTimeout = 100.millis.dilated,\n            nrOfRetries = 2,\n            retryDelay = 100.millis.dilated,\n            refreshInterval = 1.second.dilated,\n            ttlFactor = 1.5,\n            maxNrOfSeedNodes = 3,\n            joinTimeout = 100.millis.dilated,\n            abortOnJoinTimeout = false,\n            ignoreRefreshFailures = false\n          )\n        )\n      )\n      machine ! FSM.SubscribeTransitionCallBack(monitor.ref)\n\n      monitor.expectMsgPF(hint = \"Current state GettingNodes\") {\n        case FSM.CurrentState(_, State.GettingNodes) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"GettingNodes -> RetryScheduled\") {\n        case FSM.Transition(_, State.GettingNodes, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> GettingNodes\") {\n        case FSM.Transition(_, State.RetryScheduled, State.GettingNodes) => ()\n      }\n      monitor.expectMsgPF(hint = \"GettingNodes -> RetryScheduled\") {\n        case FSM.Transition(_, State.GettingNodes, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> GettingNodes\") {\n        case FSM.Transition(_, State.RetryScheduled, State.GettingNodes) => ()\n      }\n      monitor.expectMsgPF(hint = \"GettingNodes -> Locking\") {\n        case FSM.Transition(_, State.GettingNodes, State.Locking) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"Locking -> RetryScheduled\") {\n        case FSM.Transition(_, State.Locking, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> Locking\") {\n        case FSM.Transition(_, State.RetryScheduled, State.Locking) => ()\n      }\n      monitor.expectMsgPF(hint = \"Locking -> RetryScheduled\") {\n        case FSM.Transition(_, State.Locking, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> Locking\") {\n        case FSM.Transition(_, State.RetryScheduled, State.Locking) => ()\n      }\n      monitor.expectMsgPF(hint = \"Locking -> BeforeGettingNodes\") {\n        case FSM.Transition(_, State.Locking, State.BeforeGettingNodes) => ()\n      }\n      monitor.expectMsgPF(hint = \"BeforeGettingNodes -> GettingNodes\") {\n        case FSM.Transition(_, State.BeforeGettingNodes, State.GettingNodes) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"GettingNodes -> Locking\") {\n        case FSM.Transition(_, State.GettingNodes, State.Locking) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"Locking -> Joining\") {\n        case FSM.Transition(_, State.Locking, State.Joining) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"Joining -> AddingSelf\") {\n        case FSM.Transition(_, State.Joining, State.AddingSelf) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"AddingSelf -> RetryScheduled\") {\n        case FSM.Transition(_, State.AddingSelf, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> AddingSelf\") {\n        case FSM.Transition(_, State.RetryScheduled, State.AddingSelf) => ()\n      }\n      monitor.expectMsgPF(hint = \"AddingSelf -> RetryScheduled\") {\n        case FSM.Transition(_, State.AddingSelf, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> AddingSelf\") {\n        case FSM.Transition(_, State.RetryScheduled, State.AddingSelf) => ()\n      }\n      monitor.expectMsgPF(hint = \"AddingSelf -> RefreshScheduled\") {\n        case FSM.Transition(_, State.AddingSelf, State.RefreshScheduled) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"RefreshScheduled -> Refreshing\") {\n        case FSM.Transition(_, State.RefreshScheduled, State.Refreshing) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"Refreshing -> RetryScheduled\") {\n        case FSM.Transition(_, State.Refreshing, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> Refreshing\") {\n        case FSM.Transition(_, State.RetryScheduled, State.Refreshing) => ()\n      }\n      monitor.expectMsgPF(hint = \"Refreshing -> RetryScheduled\") {\n        case FSM.Transition(_, State.Refreshing, State.RetryScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RetryScheduled -> Refreshing\") {\n        case FSM.Transition(_, State.RetryScheduled, State.Refreshing) => ()\n      }\n      monitor.expectMsgPF(hint = \"Refreshing -> RefreshScheduled\") {\n        case FSM.Transition(_, State.Refreshing, State.RefreshScheduled) => ()\n      }\n    }\n\n    \"machine won't terminate on exceeded number of retries in Refreshing (if it's specified in configuration)\" in {\n      val coordination = mock(classOf[Coordination])\n      when(coordination.getNodes()).thenReturn(\n        // delay first getNodes call for a bit, so as not to transition out of GettingNodes state too fast\n        delayed(50.millis.dilated, system.scheduler)(noNodes())\n      )\n\n      when(coordination.lock(address, 1650.millis.dilated)).thenReturn(\n        Future.successful(true)\n      )\n\n      when(coordination.addSelf(address, 1500.millis.dilated)).thenReturn(\n        Future.successful(Done)\n      )\n\n      when(coordination.refresh(address, 1500.millis.dilated)).thenReturn(\n        Future.successful(Done),\n        delayed(1.hour.dilated, system.scheduler)(boom()),\n        boom(),\n        boom(),\n        Future.successful(Done)\n      )\n\n      val nrOfRetries = 2\n      val monitor     = TestProbe()\n      val machine = system.actorOf(\n        Props(\n          new ConstructrMachine(\n            selfNode = address,\n            coordination = coordination,\n            coordinationTimeout = 100.millis.dilated,\n            nrOfRetries = nrOfRetries,\n            retryDelay = 100.millis.dilated,\n            refreshInterval = 1.second.dilated,\n            ttlFactor = 1.5,\n            maxNrOfSeedNodes = 3,\n            joinTimeout = 100.millis.dilated,\n            abortOnJoinTimeout = false,\n            ignoreRefreshFailures = true\n          )\n        )\n      )\n      machine ! FSM.SubscribeTransitionCallBack(monitor.ref)\n\n      monitor.expectMsgPF(hint = \"Current state GettingNodes\") {\n        case FSM.CurrentState(_, State.GettingNodes) => ()\n      }\n      monitor.expectMsgPF(hint = \"GettingNodes -> Locking\") {\n        case FSM.Transition(_, State.GettingNodes, State.Locking) => ()\n      }\n      monitor.expectMsgPF(hint = \"Locking -> Joining\") {\n        case FSM.Transition(_, State.Locking, State.Joining) => ()\n      }\n      monitor.expectMsgPF(hint = \"Joining -> AddingSelf\") {\n        case FSM.Transition(_, State.Joining, State.AddingSelf) => ()\n      }\n      monitor.expectMsgPF(hint = \"AddingSelf -> RefreshScheduled\") {\n        case FSM.Transition(_, State.AddingSelf, State.RefreshScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RefreshScheduled -> Refreshing\") {\n        case FSM.Transition(_, State.RefreshScheduled, State.Refreshing) => ()\n      }\n\n      monitor.expectMsgPF(hint = \"Refreshing -> RefreshScheduled\") {\n        case FSM.Transition(_, State.Refreshing, State.RefreshScheduled) => ()\n      }\n      monitor.expectMsgPF(hint = \"RefreshScheduled -> Refreshing\") {\n        case FSM.Transition(_, State.RefreshScheduled, State.Refreshing) => ()\n      }\n\n      (1 to nrOfRetries + 1) foreach { _ =>\n        monitor.expectMsgPF(hint = \"Refreshing -> RetryScheduled\") {\n          case FSM.Transition(_, State.Refreshing, State.RetryScheduled) => ()\n        }\n        monitor.expectMsgPF(hint = \"RetryScheduled -> Refreshing\") {\n          case FSM.Transition(_, State.RetryScheduled, State.Refreshing) => ()\n        }\n      }\n      monitor.expectMsgPF(hint = \"Refreshing -> RefreshScheduled\") {\n        case FSM.Transition(_, State.Refreshing, State.RefreshScheduled) => ()\n      }\n    }\n  }\n\n  override protected def afterAll(): Unit = {\n    Await.ready(system.terminate, Duration.Inf)\n    super.afterAll()\n  }\n\n  private def boom() = Future.failed(new Exception(\"BOOM\"))\n\n  private def noNodes() = Future.successful(Set.empty[Address])\n}\n"
  },
  {
    "path": "core/src/test/scala/de/heikoseeberger/constructr/testutil/CoordinationInfo.scala",
    "content": "/*\n * Copyright 2015 Heiko Seeberger\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage de.heikoseeberger.constructr.testutil\n\nobject CoordinationInfo {\n\n  def host: String = {\n    val dockerHostPattern = \"\"\"tcp://(\\S+):\\d{1,5}\"\"\".r\n    sys.env\n      .get(\"DOCKER_HOST\")\n      .collect({ case dockerHostPattern(address) => address })\n      .getOrElse(\"127.0.0.1\")\n  }\n\n  def port: Int = 2379\n\n}\n"
  },
  {
    "path": "project/build.properties",
    "content": "sbt.version = 1.1.1\n"
  },
  {
    "path": "project/plugins.sbt",
    "content": "addSbtPlugin(\"com.dwijnand\"      % \"sbt-travisci\"  % \"1.1.1\")\naddSbtPlugin(\"com.jsuereth\"      % \"sbt-pgp\"       % \"1.1.0\")\naddSbtPlugin(\"com.lucidchart\"    % \"sbt-scalafmt\"  % \"1.14\")\naddSbtPlugin(\"com.typesafe.sbt\"  % \"sbt-git\"       % \"0.9.3\")\naddSbtPlugin(\"com.typesafe.sbt\"  % \"sbt-multi-jvm\" % \"0.4.0\")\naddSbtPlugin(\"de.heikoseeberger\" % \"sbt-header\"    % \"5.0.0\")\naddSbtPlugin(\"org.foundweekends\" % \"sbt-bintray\"   % \"0.5.1\")\n\nlibraryDependencies += \"org.slf4j\" % \"slf4j-nop\" % \"1.7.25\"  // Needed by sbt-git\n"
  },
  {
    "path": "shell-prompt.sbt",
    "content": "shellPrompt.in(ThisBuild) := { state =>\n  val project = Project.extract(state).currentRef.project\n  s\"[$project]> \"\n}\n"
  }
]