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