├── .github
├── dependabot.yml
└── workflows
│ ├── ci.yml
│ └── release.yml
├── .gitignore
├── LICENSE
├── README.md
├── build.gradle.kts
├── gradle
├── libs.versions.toml
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── settings.gradle.kts
└── src
├── main
├── java
│ └── pl
│ │ └── allegro
│ │ └── tech
│ │ └── boot
│ │ └── leader
│ │ └── only
│ │ ├── LeaderOnlyBeanPostProcessor.java
│ │ ├── LeaderOnlyConfiguration.java
│ │ ├── LeadershipProxyFactory.java
│ │ ├── api
│ │ ├── ConnectionStringCannotBeEmptyException.java
│ │ ├── CuratorLeadershipCustomizer.java
│ │ ├── Leader.java
│ │ ├── LeaderLatchCannotStartException.java
│ │ ├── LeaderLatchCannotStopException.java
│ │ ├── LeaderOnly.java
│ │ ├── Leadership.java
│ │ ├── LeadershipAcquisitionCallback.java
│ │ ├── LeadershipChangeCallbacks.java
│ │ ├── LeadershipFactory.java
│ │ └── LeadershipLossCallback.java
│ │ └── curator
│ │ ├── ConnectionStringConverter.java
│ │ ├── CuratorLeadership.java
│ │ ├── CuratorLeadershipConfiguration.java
│ │ ├── CuratorLeadershipFactoryImpl.java
│ │ └── CuratorLeadershipProperties.java
└── resources
│ └── META-INF
│ └── spring
│ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports
└── test
└── java
└── pl
└── allegro
└── tech
└── boot
└── leader
└── only
├── api
├── LeaderChangeCallbacksTest.java
├── LeaderOnlyTest.java
└── TestLeadership.java
├── curator
├── ConnectionStringConverterTest.java
└── CuratorLeadershipTest.java
└── fixtures
├── SampleApplication.java
└── SampleLeaderOnlyExecutor.java
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "gradle"
4 | directory: "/"
5 | schedule:
6 | interval: weekly
7 | open-pull-requests-limit: 10
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Java CI with Gradle
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | paths-ignore:
7 | - 'README.md'
8 | pull_request:
9 |
10 | jobs:
11 | build:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v4
15 | - uses: actions/setup-java@v4
16 | with:
17 | distribution: 'temurin'
18 | java-version: 17
19 | - uses: gradle/actions/setup-gradle@v4
20 | - run: ./gradlew check
21 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Publish package
2 |
3 | on:
4 | release:
5 | types: [ created ]
6 |
7 | jobs:
8 | publish:
9 |
10 | runs-on: ubuntu-latest
11 | steps:
12 | - uses: actions/checkout@v4
13 | - uses: actions/setup-java@v4
14 | with:
15 | distribution: 'temurin'
16 | java-version: 17
17 | - uses: gradle/actions/setup-gradle@v4
18 | - run: ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository
19 | env:
20 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }}
21 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }}
22 | GPG_KEY_ID: ${{ secrets.GPG_KEY_ID }}
23 | GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }}
24 | GPG_PRIVATE_KEY_PASSWORD: ${{ secrets.GPG_PRIVATE_KEY_PASSWORD }}
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore Gradle project-specific cache directory
2 | .gradle
3 |
4 | # Ignore Gradle build output directory
5 | build
6 |
7 | .idea
8 |
9 | .gradletasknamecache
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Leader Only Spring Boot Starter
2 |
3 | [](https://github.com/allegro/leader-only-spring-boot-starter/actions/workflows/ci.yml)
4 | 
5 |
6 | Sometimes it is crucial to perform some action only on one application node.
7 | This library makes this boring task easy.
8 |
9 | - Integrates with [Spring Boot 3](https://github.com/spring-projects/spring-boot)
10 | - Leverages [Apache Curator](https://curator.apache.org/)
11 | - Handles multiple locks at once
12 |
13 | ## Installation
14 |
15 | ### Maven
16 |
17 | ```xml
18 |
19 |
20 | pl.allegro.tech.boot
21 | leader-only-spring-boot-starter
22 | 1.1.0
23 |
24 |
25 | org.apache.zookeeper
26 | zookeeper
27 | 3.9.0
28 |
29 |
30 | ```
31 |
32 | ### Gradle
33 |
34 | ```groovy
35 | dependecies {
36 | implementation "pl.allegro.tech:leader-only-spring-boot-starter:1.1.0"
37 | implementation "org.apache.zookeeper:zookeeper:3.9.0"
38 | }
39 | ```
40 |
41 | ## Usage
42 |
43 | ```java
44 | import pl.allegro.tech.boot.leader.only.api.Leader;
45 | import pl.allegro.tech.boot.leader.only.api.LeaderOnly;
46 |
47 | @Leader("leader-identifier") // creates new leader latch with identifier
48 | public class Sample {
49 |
50 | @LeaderOnly
51 | public Integer performActionOnlyOnLeader() {
52 | return veryExpensiveOperation(); // this will be performed only at leader node
53 | }
54 |
55 | public Integer performActionOnEveryNode() {
56 | return somethingCheapToPerform(); // this will be performed at all nodes
57 | }
58 | }
59 | ```
60 |
61 | `@Leader` annotation enhances `@Component` and will add a candidate
62 | for auto-detection when using annotation-based configuration and classpath scanning.
63 |
64 | It is also possible to handle leadership status changes. To do so, bean annotated with `@Leader` has to
65 | implement `LeadershipChangeCallbacks` interface.
66 |
67 | ```java
68 | import pl.allegro.tech.boot.leader.only.api.Leader;
69 | import pl.allegro.tech.boot.leader.only.api.LeaderOnly;
70 | import pl.allegro.tech.boot.leader.only.api.LeadershipChangeCallbacks;
71 |
72 | @Leader("leader-identifier") // creates new leader latch with identifier
73 | public class Sample implements LeadershipChangeCallbacks {
74 |
75 | @LeaderOnly
76 | public Integer performActionOnlyOnLeader() {
77 | return veryExpensiveOperation(); // this will be performed only at leader node
78 | }
79 |
80 | public void onLeadershipAcquisition() {
81 | leadershipSetUp(); // this will be performed when node becomes a leader
82 | }
83 |
84 | public void onLeadershipLoss() {
85 | leadershipCleanUp(); // this will be performed when node stops being a leader
86 | }
87 |
88 | public Integer performActionOnEveryNode() {
89 | return somethingCheapToPerform(); // this will be performed at all nodes
90 | }
91 | }
92 | ```
93 |
94 | ## Configuration
95 |
96 | ```yaml
97 | curator-leadership:
98 | connection-string: localhost:2181 # only required property
99 | namespace: /leader-only
100 | timeout:
101 | session: 100ms
102 | connection: 100ms
103 | wait-for-shutdown: 100ms
104 | retry:
105 | max-retries: 3
106 | max-sleep-time: 1s
107 | base-sleep-time: 200ms
108 | auth:
109 | scheme: digest
110 | username: username
111 | password: password
112 | ```
113 |
114 | [Apache Zookeeper](https://zookeeper.apache.org/) &
115 | [Apache Curator](https://curator.apache.org/)
116 | are technologies that drives selecting leader.
117 |
118 | ## What if you don't want to use Zookeeper?
119 |
120 | You can make your own `Leadership` implementation and add your `LeadershipFactory` bean to Spring context.
121 | If you want to know more, check out this [example](src/test/java/pl/allegro/tech/boot/leader/only/api/LeaderOnlyTest.java).
122 |
--------------------------------------------------------------------------------
/build.gradle.kts:
--------------------------------------------------------------------------------
1 | import org.gradle.api.tasks.testing.logging.TestExceptionFormat
2 | import java.time.Duration
3 |
4 | plugins {
5 | `java-library`
6 | `maven-publish`
7 | alias(libs.plugins.springBoot)
8 | alias(libs.plugins.springDependencyManagement)
9 | alias(libs.plugins.axionRelease)
10 | alias(libs.plugins.nexusPublish)
11 | signing
12 | }
13 |
14 | repositories {
15 | mavenCentral()
16 | }
17 |
18 | group = "pl.allegro.tech.boot"
19 | version = scmVersion.version
20 |
21 | java {
22 | withSourcesJar()
23 | withJavadocJar()
24 | toolchain {
25 | languageVersion.set(JavaLanguageVersion.of(17))
26 | }
27 | }
28 |
29 | dependencies {
30 | annotationProcessor("org.springframework.boot:spring-boot-configuration-processor")
31 |
32 | api("org.springframework.boot:spring-boot-starter-aop")
33 | api("org.springframework.boot:spring-boot-autoconfigure")
34 | api(libs.bundles.curator)
35 |
36 | testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine")
37 |
38 | testImplementation(platform(libs.testcontainers))
39 | testImplementation("org.springframework.boot:spring-boot")
40 | testImplementation("org.springframework.boot:spring-boot-starter-test")
41 | testImplementation("org.testcontainers:testcontainers")
42 | testImplementation("org.testcontainers:junit-jupiter")
43 | testImplementation("org.junit.jupiter:junit-jupiter-api")
44 | testImplementation(libs.awaitility)
45 | testImplementation(libs.zookeeper)
46 | }
47 |
48 | tasks.bootJar {
49 | enabled = false
50 | }
51 |
52 | tasks.jar {
53 | enabled = true
54 | }
55 |
56 | tasks.test {
57 | useJUnitPlatform()
58 | testLogging {
59 | events("passed", "skipped", "failed")
60 | exceptionFormat = TestExceptionFormat.FULL
61 | }
62 | }
63 |
64 | publishing {
65 | publications {
66 | create("sonatype") {
67 | from(components["java"])
68 | pom {
69 | name = "leader-only-spring-boot-starter"
70 | description = "Spring Boot starter for leader only processing"
71 | url = "https://github.com/allegro/leader-only-spring-boot-starter"
72 | licenses {
73 | license {
74 | name = "The Apache License, Version 2.0"
75 | url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
76 | }
77 | }
78 | developers {
79 | developer {
80 | id = "wpanas"
81 | name = "Waldemar Panas"
82 | }
83 | }
84 | scm {
85 | connection = "scm:git@github.com:allegro/leader-only-spring-boot-starter.git"
86 | developerConnection = "scm:git@github.com:allegro/leader-only-spring-boot-starter.git"
87 | url = "https://github.com/allegro/leader-only-spring-boot-starter"
88 | }
89 | }
90 | }
91 | }
92 | repositories {
93 | maven {
94 | val releasesRepoUrl = uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/")
95 | val snapshotsRepoUrl = uri("https://oss.sonatype.org/content/repositories/snapshots/")
96 | url = if (version.toString().endsWith("SNAPSHOT")) snapshotsRepoUrl else releasesRepoUrl
97 | }
98 | }
99 | }
100 |
101 | nexusPublishing {
102 | connectTimeout = Duration.ofMinutes(10)
103 | clientTimeout = Duration.ofMinutes(10)
104 | repositories {
105 | sonatype {
106 | username.set(System.getenv("SONATYPE_USERNAME"))
107 | password.set(System.getenv("SONATYPE_PASSWORD"))
108 | }
109 | }
110 | transitionCheckOptions {
111 | maxRetries.set(30)
112 | delayBetween.set(Duration.ofSeconds(45))
113 | }
114 | }
115 |
116 | if (System.getenv("GPG_KEY_ID") != null) {
117 | signing {
118 | useInMemoryPgpKeys(
119 | System.getenv("GPG_KEY_ID"),
120 | System.getenv("GPG_PRIVATE_KEY"),
121 | System.getenv("GPG_PRIVATE_KEY_PASSWORD")
122 | )
123 | sign(publishing.publications)
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/gradle/libs.versions.toml:
--------------------------------------------------------------------------------
1 | [versions]
2 | curator = "5.7.0"
3 | junit = "5.12.2"
4 | testcontainers = "1.20.1"
5 | awaitility = "4.2.1"
6 | zookeeper = "3.9.2"
7 |
8 | [libraries]
9 | curator-recipes = { module = "org.apache.curator:curator-recipes", version.ref = "curator" }
10 | curator-framework = { module = "org.apache.curator:curator-framework", version.ref = "curator" }
11 | junit = { module = "org.junit:junit-bom", version.ref = "junit" }
12 | awaitility = { module = "org.awaitility:awaitility", version.ref = "awaitility" }
13 | testcontainers = { module = "org.testcontainers:testcontainers-bom", version.ref = "testcontainers" }
14 | zookeeper = { module = "org.apache.zookeeper:zookeeper", version.ref = "zookeeper" }
15 |
16 | [bundles]
17 | curator = ["curator-recipes", "curator-framework"]
18 |
19 | [plugins]
20 | springBoot = { id = "org.springframework.boot", version = "3.4.4" }
21 | springDependencyManagement = { id = "io.spring.dependency-management", version = "1.1.7" }
22 | axionRelease = { id = "pl.allegro.tech.build.axion-release", version = "1.18.3" }
23 | nexusPublish = { id = "io.github.gradle-nexus.publish-plugin", version = "2.0.0" }
24 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/allegro/leader-only-spring-boot-starter/c59eb706e10237bf5cd2b857ec7f6bcecd105290/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.14-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH="\\\"\\\""
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | if ! command -v java >/dev/null 2>&1
137 | then
138 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
139 |
140 | Please set the JAVA_HOME variable in your environment to match the
141 | location of your Java installation."
142 | fi
143 | fi
144 |
145 | # Increase the maximum file descriptors if we can.
146 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
147 | case $MAX_FD in #(
148 | max*)
149 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
150 | # shellcheck disable=SC2039,SC3045
151 | MAX_FD=$( ulimit -H -n ) ||
152 | warn "Could not query maximum file descriptor limit"
153 | esac
154 | case $MAX_FD in #(
155 | '' | soft) :;; #(
156 | *)
157 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
158 | # shellcheck disable=SC2039,SC3045
159 | ulimit -n "$MAX_FD" ||
160 | warn "Could not set maximum file descriptor limit to $MAX_FD"
161 | esac
162 | fi
163 |
164 | # Collect all arguments for the java command, stacking in reverse order:
165 | # * args from the command line
166 | # * the main class name
167 | # * -classpath
168 | # * -D...appname settings
169 | # * --module-path (only if needed)
170 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
171 |
172 | # For Cygwin or MSYS, switch paths to Windows format before running java
173 | if "$cygwin" || "$msys" ; then
174 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
175 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
176 |
177 | JAVACMD=$( cygpath --unix "$JAVACMD" )
178 |
179 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
180 | for arg do
181 | if
182 | case $arg in #(
183 | -*) false ;; # don't mess with options #(
184 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
185 | [ -e "$t" ] ;; #(
186 | *) false ;;
187 | esac
188 | then
189 | arg=$( cygpath --path --ignore --mixed "$arg" )
190 | fi
191 | # Roll the args list around exactly as many times as the number of
192 | # args, so each arg winds up back in the position where it started, but
193 | # possibly modified.
194 | #
195 | # NB: a `for` loop captures its iteration list before it begins, so
196 | # changing the positional parameters here affects neither the number of
197 | # iterations, nor the values presented in `arg`.
198 | shift # remove old arg
199 | set -- "$@" "$arg" # push replacement arg
200 | done
201 | fi
202 |
203 |
204 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
205 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
206 |
207 | # Collect all arguments for the java command:
208 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
209 | # and any embedded shellness will be escaped.
210 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
211 | # treated as '${Hostname}' itself on the command line.
212 |
213 | set -- \
214 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
215 | -classpath "$CLASSPATH" \
216 | -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
217 | "$@"
218 |
219 | # Stop when "xargs" is not available.
220 | if ! command -v xargs >/dev/null 2>&1
221 | then
222 | die "xargs is not available"
223 | fi
224 |
225 | # Use "xargs" to parse quoted args.
226 | #
227 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
228 | #
229 | # In Bash we could simply go:
230 | #
231 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
232 | # set -- "${ARGS[@]}" "$@"
233 | #
234 | # but POSIX shell has neither arrays nor command substitution, so instead we
235 | # post-process each arg (as a line of input to sed) to backslash-escape any
236 | # character that might be a shell metacharacter, then use eval to reverse
237 | # that process (while maintaining the separation between arguments), and wrap
238 | # the whole thing up as a single "set" statement.
239 | #
240 | # This will of course break if any of these variables contains a newline or
241 | # an unmatched quote.
242 | #
243 |
244 | eval "set -- $(
245 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
246 | xargs -n1 |
247 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
248 | tr '\n' ' '
249 | )" '"$@"'
250 |
251 | exec "$JAVACMD" "$@"
252 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/settings.gradle.kts:
--------------------------------------------------------------------------------
1 | //plugins {
2 | // /**
3 | // * This plugin allows gradle to download requested JDK version
4 | // * @see https://docs.gradle.org/current/userguide/toolchains.html#sub:download_repositories
5 | // */
6 | // id "org.gradle.toolchains.foojay-resolver-convention" version "0.7.0"
7 | //}
8 |
9 | rootProject.name = "leader-only-spring-boot-starter"
10 |
11 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/LeaderOnlyBeanPostProcessor.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only;
2 |
3 | import org.springframework.beans.factory.config.BeanPostProcessor;
4 | import org.springframework.lang.Nullable;
5 | import pl.allegro.tech.boot.leader.only.api.Leader;
6 |
7 | import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
8 |
9 | final class LeaderOnlyBeanPostProcessor implements BeanPostProcessor {
10 |
11 | private final LeadershipProxyFactory leadershipProxyFactory;
12 |
13 | public LeaderOnlyBeanPostProcessor(LeadershipProxyFactory leadershipProxyFactory) {
14 | this.leadershipProxyFactory = leadershipProxyFactory;
15 | }
16 |
17 | @Override
18 | public Object postProcessAfterInitialization(Object bean, @Nullable String beanName) {
19 | Leader annotation = findAnnotation(bean.getClass(), Leader.class);
20 |
21 | if (annotation == null) {
22 | return bean;
23 | }
24 |
25 | return leadershipProxyFactory.getProxy(bean, annotation.value());
26 | }
27 | }
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/LeaderOnlyConfiguration.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only;
2 |
3 | import org.springframework.boot.autoconfigure.AutoConfiguration;
4 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
5 | import org.springframework.context.annotation.Bean;
6 | import org.springframework.context.annotation.Configuration;
7 | import pl.allegro.tech.boot.leader.only.api.LeadershipFactory;
8 |
9 | @AutoConfiguration
10 | public class LeaderOnlyConfiguration {
11 | @Bean
12 | LeadershipProxyFactory leaderOnlyProxyFactory(LeadershipFactory leadershipFactory) {
13 | return new LeadershipProxyFactory(leadershipFactory);
14 | }
15 |
16 | @Bean
17 | @ConditionalOnBean(LeadershipProxyFactory.class)
18 | LeaderOnlyBeanPostProcessor leaderOnlyBeanPostProcessor(LeadershipProxyFactory leadershipProxyFactory) {
19 | return new LeaderOnlyBeanPostProcessor(leadershipProxyFactory);
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/LeadershipProxyFactory.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only;
2 |
3 | import org.aopalliance.intercept.MethodInterceptor;
4 | import org.aopalliance.intercept.MethodInvocation;
5 | import org.slf4j.Logger;
6 | import org.springframework.aop.framework.ProxyFactory;
7 | import org.springframework.lang.NonNull;
8 | import pl.allegro.tech.boot.leader.only.api.LeaderOnly;
9 | import pl.allegro.tech.boot.leader.only.api.Leadership;
10 | import pl.allegro.tech.boot.leader.only.api.LeadershipAcquisitionCallback;
11 | import pl.allegro.tech.boot.leader.only.api.LeadershipFactory;
12 | import pl.allegro.tech.boot.leader.only.api.LeadershipLossCallback;
13 |
14 | import java.io.Closeable;
15 |
16 | import static org.slf4j.LoggerFactory.getLogger;
17 | import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
18 |
19 | final class LeadershipProxyFactory {
20 | private static final Logger logger = getLogger(LeadershipProxyFactory.class);
21 |
22 | private final LeadershipFactory leadershipFactory;
23 |
24 | LeadershipProxyFactory(LeadershipFactory leadershipFactory) {
25 | this.leadershipFactory = leadershipFactory;
26 | }
27 |
28 | @SuppressWarnings("unchecked")
29 | T getProxy(@NonNull T object, @NonNull String path) {
30 | Leadership leadership = leadershipFactory.of(path);
31 | initializeCallbacks(object, leadership);
32 | return (T) createProxy(object, leadership).getProxy();
33 | }
34 |
35 | private void initializeCallbacks(@NonNull T object, @NonNull Leadership leadership) {
36 | String canonicalName = object.getClass().getCanonicalName();
37 | if (object instanceof LeadershipAcquisitionCallback) {
38 | leadership.registerLeadershipAcquisitionCallback(() ->
39 | ((LeadershipAcquisitionCallback)object).onLeadershipAcquisition());
40 | logger.info("{} registered as leadership acquisition callback", canonicalName);
41 | }
42 | if (object instanceof LeadershipLossCallback) {
43 | leadership.registerLeadershipLossCallback(() ->
44 | ((LeadershipLossCallback)object).onLeadershipLoss());
45 | logger.info("{} registered as leadership loss callback", canonicalName);
46 | }
47 | }
48 |
49 | private ProxyFactory createProxy(@NonNull T object, @NonNull Leadership leadership) {
50 | ProxyFactory proxyFactory = new ProxyFactory();
51 | proxyFactory.setTargetClass(object.getClass());
52 | proxyFactory.setProxyTargetClass(true);
53 | proxyFactory.setTarget(object);
54 | proxyFactory.addAdvice(new LeaderOnlyMethodInterceptor(leadership));
55 | proxyFactory.addInterface(Closeable.class);
56 | return proxyFactory;
57 | }
58 |
59 | private static final class LeaderOnlyMethodInterceptor implements MethodInterceptor {
60 | private final Leadership leadership;
61 |
62 | public LeaderOnlyMethodInterceptor(Leadership leadership) {
63 | this.leadership = leadership;
64 | }
65 |
66 | @Override
67 | public Object invoke(MethodInvocation invocation) throws Throwable {
68 | LeaderOnly annotation = findAnnotation(invocation.getMethod(), LeaderOnly.class);
69 |
70 | if (annotation != null) {
71 | if (leadership.hasLeadership()) {
72 | return invocation.proceed();
73 | }
74 |
75 | return null;
76 | } else {
77 | return invocation.proceed();
78 | }
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/ConnectionStringCannotBeEmptyException.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | /**
4 | * Thrown when connection string is empty.
5 | */
6 | public final class ConnectionStringCannotBeEmptyException extends IllegalArgumentException {
7 | /**
8 | * Creates new instance of {@link ConnectionStringCannotBeEmptyException}.
9 | */
10 | public ConnectionStringCannotBeEmptyException() {
11 | super("Provided connection string cannot be empty");
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/CuratorLeadershipCustomizer.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import org.apache.curator.framework.CuratorFrameworkFactory;
4 |
5 | /**
6 | * Customizer for CuratorFrameworkFactory.Builder
7 | */
8 | public interface CuratorLeadershipCustomizer {
9 | /**
10 | * Customize CuratorFrameworkFactory.Builder
11 | *
12 | * @param builder CuratorFrameworkFactory.Builder
13 | */
14 | void customize(CuratorFrameworkFactory.Builder builder);
15 | }
16 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/Leader.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import org.springframework.stereotype.Component;
4 |
5 | import java.lang.annotation.ElementType;
6 | import java.lang.annotation.Retention;
7 | import java.lang.annotation.RetentionPolicy;
8 | import java.lang.annotation.Target;
9 |
10 | /**
11 | * Leader annotation.
12 | */
13 | @Component
14 | @Target(ElementType.TYPE)
15 | @Retention(RetentionPolicy.RUNTIME)
16 | public @interface Leader {
17 | /** @return leader name */
18 | String value();
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeaderLatchCannotStartException.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public class LeaderLatchCannotStartException extends IllegalStateException {
4 | public LeaderLatchCannotStartException(Exception e) {
5 | super("Cannot start LeaderLatch", e);
6 | }
7 |
8 | public LeaderLatchCannotStartException() {
9 | super("Cannot start LeaderLatch due timeout");
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeaderLatchCannotStopException.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public class LeaderLatchCannotStopException extends IllegalStateException {
4 | public LeaderLatchCannotStopException(Exception e) {
5 | super("Cannot stop LeaderLatch", e);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeaderOnly.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import java.lang.annotation.ElementType;
4 | import java.lang.annotation.Retention;
5 | import java.lang.annotation.RetentionPolicy;
6 | import java.lang.annotation.Target;
7 |
8 | @Target(ElementType.METHOD)
9 | @Retention(RetentionPolicy.RUNTIME)
10 | public @interface LeaderOnly {
11 | }
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/Leadership.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public interface Leadership {
4 | boolean hasLeadership();
5 |
6 | void registerLeadershipAcquisitionCallback(Runnable runnable);
7 |
8 | void registerLeadershipLossCallback(Runnable runnable);
9 | }
10 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeadershipAcquisitionCallback.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public interface LeadershipAcquisitionCallback {
4 |
5 | void onLeadershipAcquisition();
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeadershipChangeCallbacks.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public interface LeadershipChangeCallbacks extends LeadershipAcquisitionCallback, LeadershipLossCallback {
4 | }
5 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeadershipFactory.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import org.springframework.lang.NonNull;
4 |
5 | public interface LeadershipFactory {
6 | Leadership of(@NonNull String path);
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/api/LeadershipLossCallback.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | public interface LeadershipLossCallback {
4 |
5 | void onLeadershipLoss();
6 |
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/curator/ConnectionStringConverter.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
4 | import org.springframework.core.convert.converter.Converter;
5 | import org.springframework.lang.NonNull;
6 | import org.springframework.lang.Nullable;
7 | import org.springframework.util.StringUtils;
8 | import pl.allegro.tech.boot.leader.only.curator.CuratorLeadershipProperties.ConnectionString;
9 |
10 | @ConfigurationPropertiesBinding
11 | class ConnectionStringConverter implements Converter {
12 | @Nullable
13 | @Override
14 | public ConnectionString convert(@NonNull String source) {
15 | if (StringUtils.hasText(source)) {
16 | return new ConnectionString(source);
17 | }
18 |
19 | return null;
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/curator/CuratorLeadership.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.apache.curator.framework.recipes.leader.LeaderLatch;
4 | import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
5 | import org.slf4j.Logger;
6 | import pl.allegro.tech.boot.leader.only.api.LeaderLatchCannotStartException;
7 | import pl.allegro.tech.boot.leader.only.api.LeaderLatchCannotStopException;
8 | import pl.allegro.tech.boot.leader.only.api.Leadership;
9 |
10 | import java.io.Closeable;
11 | import java.io.IOException;
12 | import java.net.InetAddress;
13 | import java.net.UnknownHostException;
14 | import java.util.ArrayList;
15 | import java.util.List;
16 | import java.util.concurrent.ExecutorService;
17 | import java.util.concurrent.Executors;
18 |
19 | import static org.slf4j.LoggerFactory.getLogger;
20 |
21 | final class CuratorLeadership implements Leadership, Closeable {
22 |
23 | private static final Logger logger = getLogger(CuratorLeadership.class);
24 |
25 | private final LeaderLatch leaderLatch;
26 | private final List leadershipAcquisitionCallbacks = new ArrayList<>();
27 | private final List leadershipLossCallbacks = new ArrayList<>();
28 | private final ExecutorService callbacksExecutor = Executors.newSingleThreadExecutor();
29 |
30 | public CuratorLeadership(String leaderLatchPath, LeaderLatch leaderLatch) {
31 | this.leaderLatch = leaderLatch;
32 |
33 | try {
34 | leaderLatch.start();
35 | } catch (Exception e) {
36 | throw new LeaderLatchCannotStartException(e);
37 | }
38 |
39 | leaderLatch.addListener(new LeaderLatchListener() {
40 | final String hostname = resolveHostname();
41 |
42 | @Override
43 | public void isLeader() {
44 | logger.info("{} is selected for the leader of {}", hostname, leaderLatchPath);
45 | leadershipAcquisitionCallbacks.forEach(callbacksExecutor::submit);
46 | logger.info("executed {} callback(s) on leadership acquisition of {} on {}",
47 | leadershipAcquisitionCallbacks.size(), leaderLatchPath, hostname);
48 | }
49 |
50 | @Override
51 | public void notLeader() {
52 | logger.info("{} is no longer the leader of {}", hostname, leaderLatchPath);
53 | leadershipLossCallbacks.forEach(callbacksExecutor::submit);
54 | logger.info("executed {} callback(s) on leadership loss of {} on {}",
55 | leadershipLossCallbacks.size(), leaderLatchPath, hostname);
56 | }
57 |
58 | private String resolveHostname() {
59 | try {
60 | return InetAddress.getLocalHost().getHostName();
61 | } catch (UnknownHostException e) {
62 | return "???";
63 | }
64 | }
65 | });
66 | }
67 |
68 | @Override
69 | public boolean hasLeadership() {
70 | return leaderLatch.hasLeadership();
71 | }
72 |
73 | @Override
74 | public void registerLeadershipAcquisitionCallback(Runnable callback) {
75 | leadershipAcquisitionCallbacks.add(callback);
76 | }
77 |
78 | @Override
79 | public void registerLeadershipLossCallback(Runnable callback) {
80 | leadershipLossCallbacks.add(callback);
81 | }
82 |
83 | @Override
84 | public void close() {
85 | try {
86 | leaderLatch.close();
87 | } catch (IOException e) {
88 | throw new LeaderLatchCannotStopException(e);
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/curator/CuratorLeadershipConfiguration.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.apache.curator.drivers.TracerDriver;
4 | import org.apache.curator.ensemble.EnsembleProvider;
5 | import org.apache.curator.framework.CuratorFramework;
6 | import org.apache.curator.framework.CuratorFrameworkFactory;
7 | import org.springframework.boot.autoconfigure.AutoConfiguration;
8 | import org.springframework.boot.autoconfigure.AutoConfigureBefore;
9 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
11 | import org.springframework.boot.context.properties.EnableConfigurationProperties;
12 | import org.springframework.context.annotation.Bean;
13 | import org.springframework.context.annotation.Configuration;
14 | import pl.allegro.tech.boot.leader.only.LeaderOnlyConfiguration;
15 | import pl.allegro.tech.boot.leader.only.api.CuratorLeadershipCustomizer;
16 | import pl.allegro.tech.boot.leader.only.api.LeadershipFactory;
17 |
18 | import java.util.Optional;
19 | import java.util.stream.Stream;
20 |
21 | import static org.apache.curator.framework.CuratorFrameworkFactory.builder;
22 |
23 | /**
24 | * Configuration for Curator based leadership.
25 | */
26 | @AutoConfiguration
27 | @AutoConfigureBefore(LeaderOnlyConfiguration.class)
28 | @EnableConfigurationProperties(CuratorLeadershipProperties.class)
29 | public class CuratorLeadershipConfiguration {
30 | @Bean(initMethod = "start", destroyMethod = "close")
31 | @ConditionalOnProperty(prefix = "curator-leadership", name = "connection-string")
32 | CuratorFramework leaderOnlyCuratorClient(
33 | CuratorLeadershipProperties properties,
34 | Optional> optionalCuratorFrameworkCustomizerProvider,
35 | Optional optionalEnsembleProvider,
36 | Optional optionalTracerDriverProvider) {
37 | final CuratorFrameworkFactory.Builder builder = builder()
38 | .connectString(properties.getConnectionString())
39 | .retryPolicy(properties.getRetryPolicy());
40 |
41 | properties.getAuth()
42 | .ifPresent(auth -> builder.authorization(auth.getSchema(), auth.getCredentials()));
43 |
44 | properties.getSessionTimeoutMs()
45 | .ifPresent(builder::sessionTimeoutMs);
46 |
47 | properties.getConnectionTimeoutMs()
48 | .ifPresent(builder::connectionTimeoutMs);
49 |
50 | properties.getWaitForShutdownTimeoutMs()
51 | .ifPresent(builder::waitForShutdownTimeoutMs);
52 |
53 | builder.namespace(properties.getNamespace());
54 |
55 | optionalEnsembleProvider.ifPresent(builder::ensembleProvider);
56 |
57 | optionalCuratorFrameworkCustomizerProvider
58 | .ifPresent(customizers -> customizers.forEach(it -> it.customize(builder)));
59 |
60 | final CuratorFramework client = builder.build();
61 |
62 | optionalTracerDriverProvider
63 | .ifPresent(tracerDriver -> Optional.ofNullable(client.getZookeeperClient())
64 | .ifPresent(zookeeperClient -> zookeeperClient.setTracerDriver(tracerDriver)));
65 |
66 | return client;
67 | }
68 |
69 | @Bean
70 | @ConditionalOnBean(name = "leaderOnlyCuratorClient")
71 | LeadershipFactory curatorLeaderLatchFactory(CuratorFramework leaderOnlyCuratorClient) {
72 | return new CuratorLeadershipFactoryImpl(leaderOnlyCuratorClient);
73 | }
74 |
75 | @Bean
76 | ConnectionStringConverter connectionStringConverter() {
77 | return new ConnectionStringConverter();
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/curator/CuratorLeadershipFactoryImpl.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.apache.curator.framework.CuratorFramework;
4 | import org.apache.curator.framework.recipes.leader.LeaderLatch;
5 | import org.springframework.lang.NonNull;
6 | import pl.allegro.tech.boot.leader.only.api.Leadership;
7 | import pl.allegro.tech.boot.leader.only.api.LeadershipFactory;
8 |
9 | import java.io.Closeable;
10 | import java.nio.file.Paths;
11 | import java.util.concurrent.ConcurrentHashMap;
12 |
13 | final class CuratorLeadershipFactoryImpl implements LeadershipFactory, Closeable {
14 | private static final String ABSOLUTE_PATH = "/";
15 |
16 | private final ConcurrentHashMap leaderships = new ConcurrentHashMap<>();
17 |
18 | private final CuratorFramework client;
19 |
20 | public CuratorLeadershipFactoryImpl(CuratorFramework client) {
21 | this.client = client;
22 | }
23 |
24 | @Override
25 | public Leadership of(@NonNull String path) {
26 | final String absolutePath = Paths.get(ABSOLUTE_PATH, path).toString();
27 | if (!leaderships.containsKey(absolutePath)) {
28 | final LeaderLatch latch = new LeaderLatch(client, absolutePath, "", LeaderLatch.CloseMode.NOTIFY_LEADER);
29 | leaderships.put(absolutePath, new CuratorLeadership(absolutePath, latch));
30 | }
31 |
32 | return leaderships.get(absolutePath);
33 | }
34 |
35 | @Override
36 | public void close() {
37 | leaderships.values().forEach(CuratorLeadership::close);
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/main/java/pl/allegro/tech/boot/leader/only/curator/CuratorLeadershipProperties.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.apache.curator.RetryPolicy;
4 | import org.apache.curator.retry.ExponentialBackoffRetry;
5 | import org.apache.curator.retry.RetryOneTime;
6 | import org.springframework.boot.context.properties.ConfigurationProperties;
7 | import org.springframework.boot.convert.DurationUnit;
8 | import pl.allegro.tech.boot.leader.only.api.ConnectionStringCannotBeEmptyException;
9 |
10 | import java.nio.file.Path;
11 | import java.nio.file.Paths;
12 | import java.time.Duration;
13 | import java.util.Optional;
14 |
15 | import static java.time.temporal.ChronoUnit.MILLIS;
16 | import static org.springframework.util.StringUtils.hasText;
17 |
18 | @ConfigurationProperties(prefix = "curator-leadership")
19 | class CuratorLeadershipProperties {
20 | private static final Path DEFAULT_NAMESPACE = Paths.get("leader-only");
21 |
22 | private final ConnectionString connectionString;
23 | private final RetryPolicyProperties retry;
24 | private final AuthProperties auth;
25 | private final TimeoutProperties timeout;
26 | private final Path namespace;
27 |
28 | public CuratorLeadershipProperties(
29 | ConnectionString connectionString,
30 | Path namespace,
31 | RetryPolicyProperties retry,
32 | AuthProperties auth,
33 | TimeoutProperties timeout
34 | ) {
35 | this.connectionString = connectionString;
36 | this.namespace = Optional.ofNullable(namespace)
37 | .orElse(DEFAULT_NAMESPACE);
38 | this.retry = retry;
39 | this.auth = auth;
40 | this.timeout = timeout;
41 | }
42 |
43 | public String getConnectionString() {
44 | return Optional.ofNullable(connectionString)
45 | .map(ConnectionString::getValue)
46 | .orElseThrow(ConnectionStringCannotBeEmptyException::new);
47 | }
48 |
49 | public String getNamespace() {
50 | return namespace.toString();
51 | }
52 |
53 | public RetryPolicy getRetryPolicy() {
54 | return Optional.ofNullable(retry)
55 | .map(RetryPolicyProperties::getExponentialBackoffRetry)
56 | .orElseGet(() -> new RetryOneTime(100));
57 | }
58 |
59 | public Optional getAuth() {
60 | return Optional.ofNullable(auth)
61 | .filter(AuthProperties::hasCredentials);
62 | }
63 |
64 | public Optional getSessionTimeoutMs() {
65 | return Optional.ofNullable(timeout)
66 | .map(TimeoutProperties::getSession)
67 | .map(Duration::toMillis)
68 | .map(Long::intValue);
69 | }
70 |
71 | public Optional getConnectionTimeoutMs() {
72 | return Optional.ofNullable(timeout)
73 | .map(TimeoutProperties::getConnection)
74 | .map(Duration::toMillis)
75 | .map(Long::intValue);
76 | }
77 |
78 | public Optional getWaitForShutdownTimeoutMs() {
79 | return Optional.ofNullable(timeout)
80 | .map(TimeoutProperties::getWaitForShutdown)
81 | .map(Duration::toMillis)
82 | .map(Long::intValue);
83 | }
84 |
85 | static class ConnectionString {
86 | private final String value;
87 |
88 | ConnectionString(String value) {
89 | this.value = value;
90 | }
91 |
92 | public String getValue() {
93 | return value;
94 | }
95 | }
96 |
97 | static class RetryPolicyProperties {
98 | private static final int DEFAULT_BASE_SLEEP_TIME_MS = 200;
99 | private static final int DEFAULT_MAX_SLEEP_TIME_MS = 1000;
100 |
101 | private final Integer maxRetries;
102 | private final Duration maxSleepTime;
103 | private final Duration baseSleepTime;
104 |
105 | RetryPolicyProperties(Integer maxRetries, Duration maxSleepTime, Duration baseSleepTime) {
106 | this.maxRetries = Optional.ofNullable(maxRetries).orElse(3);
107 | this.maxSleepTime = maxSleepTime;
108 | this.baseSleepTime = baseSleepTime;
109 | }
110 |
111 | public RetryPolicy getExponentialBackoffRetry() {
112 | return new ExponentialBackoffRetry(getBaseSleepTime(), maxRetries, getMaxSleepTime());
113 | }
114 |
115 | private int getBaseSleepTime() {
116 | return Optional.ofNullable(baseSleepTime)
117 | .map(Duration::toMillis)
118 | .map(Long::intValue)
119 | .orElse(DEFAULT_BASE_SLEEP_TIME_MS);
120 | }
121 |
122 | private int getMaxSleepTime() {
123 | return Optional.ofNullable(maxSleepTime)
124 | .map(Duration::toMillis)
125 | .map(Long::intValue)
126 | .orElse(DEFAULT_MAX_SLEEP_TIME_MS);
127 | }
128 | }
129 |
130 | static class AuthProperties {
131 | private final String username;
132 | private final String password;
133 | private final String schema;
134 |
135 | AuthProperties(String username, String password, String schema) {
136 | this.username = username;
137 | this.password = password;
138 | this.schema = Optional.ofNullable(schema).orElse("digest");
139 | }
140 |
141 | public String getSchema() {
142 | return schema;
143 | }
144 |
145 | private boolean hasCredentials() {
146 | return hasText(username) && hasText(password);
147 | }
148 |
149 | public byte[] getCredentials() {
150 | return (username + ":" + password).getBytes();
151 | }
152 | }
153 |
154 | static class TimeoutProperties {
155 | @DurationUnit(MILLIS)
156 | private final Duration session;
157 | @DurationUnit(MILLIS)
158 | private final Duration connection;
159 | @DurationUnit(MILLIS)
160 | private final Duration waitForShutdown;
161 |
162 | TimeoutProperties(Duration session, Duration connection, Duration waitForShutdown) {
163 | this.session = session;
164 | this.connection = connection;
165 | this.waitForShutdown = waitForShutdown;
166 | }
167 |
168 | public Duration getSession() {
169 | return session;
170 | }
171 |
172 | public Duration getConnection() {
173 | return connection;
174 | }
175 |
176 | public Duration getWaitForShutdown() {
177 | return waitForShutdown;
178 | }
179 | }
180 | }
181 |
--------------------------------------------------------------------------------
/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports:
--------------------------------------------------------------------------------
1 | pl.allegro.tech.boot.leader.only.LeaderOnlyConfiguration
2 | pl.allegro.tech.boot.leader.only.curator.CuratorLeadershipConfiguration
3 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/api/LeaderChangeCallbacksTest.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import org.junit.jupiter.api.AfterEach;
4 | import org.junit.jupiter.api.Test;
5 | import org.springframework.beans.factory.annotation.Autowired;
6 | import org.springframework.boot.test.context.SpringBootTest;
7 | import org.springframework.boot.test.context.TestConfiguration;
8 | import org.springframework.context.annotation.Bean;
9 | import org.springframework.context.annotation.Import;
10 | import pl.allegro.tech.boot.leader.only.fixtures.SampleApplication;
11 | import pl.allegro.tech.boot.leader.only.fixtures.SampleLeaderOnlyExecutor;
12 |
13 | import static org.junit.jupiter.api.Assertions.assertEquals;
14 |
15 | @SpringBootTest(classes = SampleApplication.class)
16 | @Import(LeaderChangeCallbacksTest.TestLeaderConfiguration.class)
17 | class LeaderChangeCallbacksTest {
18 |
19 | private static final TestLeadership TEST_LEADERSHIP = new TestLeadership();
20 |
21 | @Autowired
22 | SampleLeaderOnlyExecutor underTest;
23 |
24 | @AfterEach
25 | public void cleanUp() {
26 | underTest.resetCounters();
27 | }
28 |
29 | @Test
30 | void shouldExecuteLeadershipAcquisitionCallbackWhenSetAsLeader() {
31 | TEST_LEADERSHIP.setLeadership(true);
32 |
33 | int actual = underTest.getLeadershipAcquisitionCounter();
34 |
35 | assertEquals(1, actual);
36 | }
37 |
38 | @Test
39 | void shouldNotExecuteLeadershipLossCallbackWhenSetAsLeader() {
40 | TEST_LEADERSHIP.setLeadership(true);
41 |
42 | int actual = underTest.getLeadershipLossCounter();
43 |
44 | assertEquals(0, actual);
45 | }
46 |
47 | @Test
48 | void shouldExecuteLeadershipLossCallbackWhenSetAsNotLeader() {
49 | TEST_LEADERSHIP.setLeadership(false);
50 |
51 | int actual = underTest.getLeadershipLossCounter();
52 |
53 | assertEquals(1, actual);
54 | }
55 |
56 | @Test
57 | void shouldNotExecuteLeadershipAcquisitionCallbackWhenSetAsNotLeader() {
58 | TEST_LEADERSHIP.setLeadership(false);
59 |
60 | int actual = underTest.getLeadershipAcquisitionCounter();
61 |
62 | assertEquals(0, actual);
63 | }
64 |
65 | @TestConfiguration
66 | static class TestLeaderConfiguration {
67 | @Bean
68 | LeadershipFactory testLeadershipFactory() {
69 | return path -> TEST_LEADERSHIP;
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/api/LeaderOnlyTest.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.junit.jupiter.params.ParameterizedTest;
5 | import org.junit.jupiter.params.provider.ValueSource;
6 | import org.springframework.beans.factory.annotation.Autowired;
7 | import org.springframework.boot.test.context.SpringBootTest;
8 | import org.springframework.boot.test.context.TestConfiguration;
9 | import org.springframework.context.annotation.Bean;
10 | import org.springframework.context.annotation.Import;
11 | import pl.allegro.tech.boot.leader.only.fixtures.SampleApplication;
12 | import pl.allegro.tech.boot.leader.only.fixtures.SampleLeaderOnlyExecutor;
13 |
14 | import static org.junit.jupiter.api.Assertions.assertEquals;
15 | import static org.junit.jupiter.api.Assertions.assertNull;
16 |
17 | @SpringBootTest(classes = SampleApplication.class)
18 | @Import(LeaderOnlyTest.TestLeaderConfiguration.class)
19 | class LeaderOnlyTest {
20 |
21 | private static final TestLeadership TEST_LEADERSHIP = new TestLeadership();
22 |
23 | @Autowired
24 | SampleLeaderOnlyExecutor underTest;
25 |
26 | @Test
27 | void shouldRunOnlyOnLeaderIfMethodHasLeaderOnlyAnnotation() {
28 | TEST_LEADERSHIP.setLeadership(true);
29 |
30 | Integer actual = underTest.calculateWhatIsTwoPlusTwo();
31 |
32 | assertEquals(4, actual);
33 | }
34 |
35 | @Test
36 | void shouldNotRunOnNotLeaderIfMethodHasLeaderOnlyAnnotation() {
37 | TEST_LEADERSHIP.setLeadership(false);
38 |
39 | Integer actual = underTest.calculateWhatIsTwoPlusTwo();
40 |
41 | assertNull(actual);
42 | }
43 |
44 | @ParameterizedTest
45 | @ValueSource(booleans = {true, false})
46 | void shouldRunRegardlessOfLeadershipIfMethodHasNoLeaderOnlyAnnotation(boolean leadership) {
47 | TEST_LEADERSHIP.setLeadership(leadership);
48 |
49 | Integer actual = underTest.calculateWhatIsOnePlusTwo();
50 |
51 | assertEquals(3, actual);
52 | }
53 |
54 | @TestConfiguration
55 | static class TestLeaderConfiguration {
56 | @Bean
57 | LeadershipFactory testLeadershipFactory() {
58 | return path -> TEST_LEADERSHIP;
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/api/TestLeadership.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.api;
2 |
3 | import java.util.ArrayList;
4 | import java.util.List;
5 |
6 | class TestLeadership implements Leadership {
7 | private boolean leadership;
8 | private final List leadershipAcquisitionCallbacks = new ArrayList<>();
9 | private final List leadershipLossCallbacks = new ArrayList<>();
10 |
11 | @Override
12 | public boolean hasLeadership() {
13 | return leadership;
14 | }
15 |
16 | @Override
17 | public void registerLeadershipAcquisitionCallback(Runnable callback) {
18 | leadershipAcquisitionCallbacks.add(callback);
19 | }
20 |
21 | @Override
22 | public void registerLeadershipLossCallback(Runnable callback) {
23 | leadershipLossCallbacks.add(callback);
24 | }
25 |
26 | public void setLeadership(boolean leadership) {
27 | if (leadership) {
28 | leadershipAcquisitionCallbacks.forEach(Runnable::run);
29 | } else {
30 | leadershipLossCallbacks.forEach(Runnable::run);
31 |
32 | }
33 | this.leadership = leadership;
34 | }
35 |
36 | private boolean isLeadershipAcquired(boolean leadership) {
37 | return !this.leadership && leadership;
38 | }
39 |
40 | private boolean isLeadershipLost(boolean leadership) {
41 | return this.leadership && !leadership;
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/curator/ConnectionStringConverterTest.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.junit.jupiter.params.ParameterizedTest;
4 | import org.junit.jupiter.params.provider.ValueSource;
5 | import pl.allegro.tech.boot.leader.only.curator.CuratorLeadershipProperties.ConnectionString;
6 |
7 | import static org.junit.jupiter.api.Assertions.assertEquals;
8 | import static org.junit.jupiter.api.Assertions.assertNotNull;
9 | import static org.junit.jupiter.api.Assertions.assertNull;
10 |
11 | class ConnectionStringConverterTest {
12 |
13 | private final ConnectionStringConverter underTest = new ConnectionStringConverter();
14 |
15 | @ParameterizedTest
16 | @ValueSource(strings = {"localhost:2181", "127.0.0.1:3000,127.0.0.1:3001"})
17 | void shouldConvertStringToConnectionString(String source) {
18 | // when
19 | final ConnectionString connectionString = underTest.convert(source);
20 |
21 | // then
22 | assertNotNull(connectionString);
23 | assertEquals(connectionString.getValue(), source);
24 | }
25 |
26 | @ParameterizedTest
27 | @ValueSource(strings = {"", " "})
28 | void shouldNotConvertEmptyStringToConnectionString(String source) {
29 | // when
30 | final ConnectionString connectionString = underTest.convert(source);
31 |
32 | // then
33 | assertNull(connectionString);
34 | }
35 | }
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/curator/CuratorLeadershipTest.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.curator;
2 |
3 | import org.junit.jupiter.api.Test;
4 | import org.springframework.beans.factory.annotation.Autowired;
5 | import org.springframework.boot.test.context.SpringBootTest;
6 | import org.springframework.test.context.DynamicPropertyRegistry;
7 | import org.springframework.test.context.DynamicPropertySource;
8 | import org.testcontainers.containers.GenericContainer;
9 | import org.testcontainers.junit.jupiter.Container;
10 | import org.testcontainers.junit.jupiter.Testcontainers;
11 | import org.testcontainers.utility.DockerImageName;
12 | import pl.allegro.tech.boot.leader.only.fixtures.SampleApplication;
13 | import pl.allegro.tech.boot.leader.only.fixtures.SampleLeaderOnlyExecutor;
14 |
15 | import static java.util.concurrent.TimeUnit.SECONDS;
16 | import static java.util.function.Predicate.isEqual;
17 | import static org.awaitility.Awaitility.await;
18 | import static org.junit.jupiter.api.Assertions.assertEquals;
19 | import static org.junit.jupiter.api.Assertions.assertTrue;
20 |
21 | @Testcontainers
22 | @SpringBootTest(classes = SampleApplication.class)
23 | class CuratorLeadershipTest {
24 |
25 | private static final int PORT = 2181;
26 |
27 | @Container
28 | public static final GenericContainer> zookeeper = new GenericContainer<>(DockerImageName.parse("zookeeper:3.6.2"))
29 | .withExposedPorts(PORT);
30 |
31 | @DynamicPropertySource
32 | static void zookeeperProperties(DynamicPropertyRegistry registry) {
33 | registry.add("curator-leadership.connection-string", () ->
34 | zookeeper.getHost() + ":" + zookeeper.getMappedPort(PORT));
35 | registry.add("curator-leadership.namespace", () -> "test/path");
36 | }
37 |
38 | @Autowired
39 | SampleLeaderOnlyExecutor underTest;
40 |
41 | @Test
42 | void shouldRespondOnlyOnLeader() {
43 | assertTrue(zookeeper.isRunning());
44 |
45 | await().atMost(5, SECONDS).until(() -> underTest.calculateWhatIsTwoPlusTwo(), isEqual(4));
46 |
47 | assertEquals(1, underTest.getLeadershipAcquisitionCounter());
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/fixtures/SampleApplication.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.fixtures;
2 |
3 | import org.springframework.boot.autoconfigure.SpringBootApplication;
4 |
5 | @SpringBootApplication
6 | public class SampleApplication {
7 | }
8 |
--------------------------------------------------------------------------------
/src/test/java/pl/allegro/tech/boot/leader/only/fixtures/SampleLeaderOnlyExecutor.java:
--------------------------------------------------------------------------------
1 | package pl.allegro.tech.boot.leader.only.fixtures;
2 |
3 | import pl.allegro.tech.boot.leader.only.api.Leader;
4 | import pl.allegro.tech.boot.leader.only.api.LeaderOnly;
5 | import pl.allegro.tech.boot.leader.only.api.LeadershipChangeCallbacks;
6 |
7 | @Leader("sample")
8 | public class SampleLeaderOnlyExecutor implements LeadershipChangeCallbacks {
9 | private int leadershipAcquisitionCounter = 0;
10 | private int leadershipLossCounter = 0;
11 |
12 | @LeaderOnly
13 | public Integer calculateWhatIsTwoPlusTwo() {
14 | return 4;
15 | }
16 |
17 | public void onLeadershipAcquisition() {
18 | leadershipAcquisitionCounter++;
19 | }
20 |
21 | public void onLeadershipLoss() {
22 | leadershipLossCounter++;
23 | }
24 |
25 | public Integer calculateWhatIsOnePlusTwo() {
26 | return 3;
27 | }
28 |
29 | public int getLeadershipAcquisitionCounter() {
30 | return leadershipAcquisitionCounter;
31 | }
32 |
33 | public int getLeadershipLossCounter() {
34 | return leadershipLossCounter;
35 | }
36 |
37 | public void resetCounters() {
38 | leadershipAcquisitionCounter = 0;
39 | leadershipLossCounter = 0;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------