├── .editorconfig
├── .gitattributes
├── .github
├── FUNDING.yml
├── dependabot.yml
├── settings.xml
└── workflows
│ ├── close_stale.yml
│ ├── codeql-analysis.yml
│ └── maven.yml
├── .gitignore
├── .mvn
└── wrapper
│ ├── MavenWrapperDownloader.java
│ └── maven-wrapper.properties
├── .travis.yml
├── .travis_after_success.sh
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── SECURITY.md
├── consul-core
├── LICENSE
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── com
│ │ └── smoketurner
│ │ └── dropwizard
│ │ └── consul
│ │ ├── ConsulBundle.java
│ │ ├── ConsulConfiguration.java
│ │ ├── ConsulFactory.java
│ │ ├── config
│ │ ├── ConsulLookup.java
│ │ └── ConsulSubstitutor.java
│ │ ├── core
│ │ ├── ConsulAdvertiser.java
│ │ └── ConsulServiceListener.java
│ │ ├── health
│ │ └── ConsulHealthCheck.java
│ │ ├── managed
│ │ └── ConsulAdvertiserManager.java
│ │ └── task
│ │ └── MaintenanceTask.java
│ └── test
│ └── java
│ └── com
│ └── smoketurner
│ └── dropwizard
│ └── consul
│ ├── ConsulBundleTest.java
│ ├── ConsulFactoryTest.java
│ ├── core
│ ├── ConsulAdvertiserTest.java
│ └── ConsulServiceListenerTest.java
│ ├── health
│ └── ConsulHealthCheckTest.java
│ └── managed
│ └── ConsulAdvertiserManagerTest.java
├── consul-example
├── LICENSE
├── example.keystore
├── hello-world.yml
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── example
│ └── helloworld
│ ├── HelloWorldApplication.java
│ ├── HelloWorldConfiguration.java
│ ├── api
│ └── Saying.java
│ └── resources
│ └── HelloWorldResource.java
├── consul-ribbon
├── LICENSE
├── pom.xml
└── src
│ └── main
│ └── java
│ └── com
│ └── smoketurner
│ └── dropwizard
│ └── consul
│ └── ribbon
│ ├── ConsulServerList.java
│ ├── ConsulServiceDiscoverer.java
│ ├── HealthyConsulServiceDiscoverer.java
│ ├── RibbonJerseyClient.java
│ ├── RibbonJerseyClientBuilder.java
│ └── RibbonJerseyClientConfiguration.java
├── maven_deploy_settings.xml
├── mvnw
├── mvnw.cmd
├── pom.xml
└── spotbugs.xml
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Configuration file for EditorConfig: http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | end_of_line = lf
7 | indent_style = space
8 | indent_size = 4
9 | insert_final_newline = true
10 | trim_trailing_whitespace = true
11 |
12 | [*.properties]
13 | charset = latin1
14 |
15 | [travis.yml]
16 | indent_size = 2
17 | indent_style = space
18 |
19 | [*.md]
20 | trim_trailing_whitespace = false
21 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text auto
2 |
3 | *.java text eol=lf
4 | *.yml text eol=lf
5 | *.xml text eol=lf
6 |
7 | *.png binary
8 | *.jpg binary
9 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: jplock # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
4 | patreon: jplock # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | custom: # Replace with a single custom sponsorship URL
9 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "maven"
4 | directory: "/"
5 | schedule:
6 | interval: "weekly"
7 | - package-ecosystem: "github-actions"
8 | directory: "/"
9 | schedule:
10 | interval: "weekly"
11 |
--------------------------------------------------------------------------------
/.github/settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 |
21 |
22 | jcenter
23 | JCenter
24 | https://jcenter.bintray.com
25 | central
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/.github/workflows/close_stale.yml:
--------------------------------------------------------------------------------
1 | name: "Close stale issues"
2 | on:
3 | schedule:
4 | - cron: "0 0 * * *"
5 | jobs:
6 | stale:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - uses: actions/stale@v8
10 | with:
11 | repo-token: ${{ secrets.GITHUB_TOKEN }}
12 | stale-issue-message: 'This issue is stale because it has been open 90 days with no activity. Remove the "stale" label or comment or this will be closed in 14 days.'
13 | stale-pr-message: 'This pull request is stale because it has been open 90 days with no activity. Remove the "stale" label or comment or this will be closed in 14 days.'
14 | days-before-stale: 90
15 | days-before-close: 14
16 |
--------------------------------------------------------------------------------
/.github/workflows/codeql-analysis.yml:
--------------------------------------------------------------------------------
1 | name: "CodeQL"
2 |
3 | on:
4 | push:
5 | branches: [master, ]
6 | pull_request:
7 | # The branches below must be a subset of the branches above
8 | branches: [master]
9 | schedule:
10 | - cron: '0 13 * * 2'
11 |
12 | jobs:
13 | analyze:
14 | name: Analyze
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - name: Checkout repository
19 | uses: actions/checkout@v3
20 | with:
21 | # We must fetch at least the immediate parents so that if this is
22 | # a pull request then we can checkout the head.
23 | fetch-depth: 2
24 |
25 | # If this run was triggered by a pull request event, then checkout
26 | # the head of the pull request instead of the merge commit.
27 | - run: git checkout HEAD^2
28 | if: ${{ github.event_name == 'pull_request' }}
29 |
30 | # Initializes the CodeQL tools for scanning.
31 | - name: Initialize CodeQL
32 | uses: github/codeql-action/init@v2
33 | # Override language selection by uncommenting this and choosing your languages
34 | with:
35 | languages: java
36 |
37 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
38 | # If this step fails, then you should remove it and run the build manually (see below)
39 | - name: Autobuild
40 | uses: github/codeql-action/autobuild@v2
41 |
42 | # ℹ️ Command-line programs to run using the OS shell.
43 | # 📚 https://git.io/JvXDl
44 |
45 | # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
46 | # and modify them (or add more) to build your code if your project
47 | # uses a compiled language
48 |
49 | #- run: |
50 | # make bootstrap
51 | # make release
52 |
53 | - name: Perform CodeQL Analysis
54 | uses: github/codeql-action/analyze@v2
55 |
--------------------------------------------------------------------------------
/.github/workflows/maven.yml:
--------------------------------------------------------------------------------
1 | name: Java CI
2 | on:
3 | push:
4 | branches:
5 | - master
6 | - release/*
7 | jobs:
8 | build:
9 | runs-on: ${{ matrix.os }}
10 | strategy:
11 | matrix:
12 | java_version: [11, 14]
13 | os: [ubuntu-latest, macOS-latest]
14 | steps:
15 | - uses: actions/checkout@v3
16 | - name: Set up JDK
17 | uses: actions/setup-java@v3
18 | with:
19 | java-version: ${{ matrix.java_version }}
20 | - name: Print Java and Maven versions
21 | run: ./mvnw -B -s .github/settings.xml -v
22 | - name: Build with Maven
23 | run: ./mvnw -B -s .github/settings.xml install -Dmaven.test.skip=true -Dmaven.javadoc.skip=true
24 | - name: Run tests
25 | run: ./mvnw -B -s .github/settings.xml verify
26 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .classpath
2 | .project
3 | .settings
4 | .idea
5 | *.iml
6 | .DS_Store
7 | *.class
8 | *.jar
9 | hs_err_pid*
10 | target
11 | dependency-reduced-pom.xml
12 |
--------------------------------------------------------------------------------
/.mvn/wrapper/MavenWrapperDownloader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2007-present the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | import java.net.*;
17 | import java.io.*;
18 | import java.nio.channels.*;
19 | import java.util.Properties;
20 |
21 | public class MavenWrapperDownloader {
22 |
23 | private static final String WRAPPER_VERSION = "0.5.5";
24 | /**
25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
26 | */
27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
29 |
30 | /**
31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
32 | * use instead of the default one.
33 | */
34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
35 | ".mvn/wrapper/maven-wrapper.properties";
36 |
37 | /**
38 | * Path where the maven-wrapper.jar will be saved to.
39 | */
40 | private static final String MAVEN_WRAPPER_JAR_PATH =
41 | ".mvn/wrapper/maven-wrapper.jar";
42 |
43 | /**
44 | * Name of the property which should be used to override the default download url for the wrapper.
45 | */
46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
47 |
48 | public static void main(String args[]) {
49 | System.out.println("- Downloader started");
50 | File baseDirectory = new File(args[0]);
51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
52 |
53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom
54 | // wrapperUrl parameter.
55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
56 | String url = DEFAULT_DOWNLOAD_URL;
57 | if(mavenWrapperPropertyFile.exists()) {
58 | FileInputStream mavenWrapperPropertyFileInputStream = null;
59 | try {
60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
61 | Properties mavenWrapperProperties = new Properties();
62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
64 | } catch (IOException e) {
65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
66 | } finally {
67 | try {
68 | if(mavenWrapperPropertyFileInputStream != null) {
69 | mavenWrapperPropertyFileInputStream.close();
70 | }
71 | } catch (IOException e) {
72 | // Ignore ...
73 | }
74 | }
75 | }
76 | System.out.println("- Downloading from: " + url);
77 |
78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
79 | if(!outputFile.getParentFile().exists()) {
80 | if(!outputFile.getParentFile().mkdirs()) {
81 | System.out.println(
82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
83 | }
84 | }
85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
86 | try {
87 | downloadFileFromURL(url, outputFile);
88 | System.out.println("Done");
89 | System.exit(0);
90 | } catch (Throwable e) {
91 | System.out.println("- Error downloading");
92 | e.printStackTrace();
93 | System.exit(1);
94 | }
95 | }
96 |
97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception {
98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
99 | String username = System.getenv("MVNW_USERNAME");
100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
101 | Authenticator.setDefault(new Authenticator() {
102 | @Override
103 | protected PasswordAuthentication getPasswordAuthentication() {
104 | return new PasswordAuthentication(username, password);
105 | }
106 | });
107 | }
108 | URL website = new URL(urlString);
109 | ReadableByteChannel rbc;
110 | rbc = Channels.newChannel(website.openStream());
111 | FileOutputStream fos = new FileOutputStream(destination);
112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
113 | fos.close();
114 | rbc.close();
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/.mvn/wrapper/maven-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.1/apache-maven-3.6.1-bin.zip
2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.5/maven-wrapper-0.5.5.jar
3 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: java
2 | os:
3 | - linux
4 | jdk:
5 | - openjdk11
6 | services: docker
7 | before_install:
8 | - rm ~/.m2/settings.xml || true
9 | - ulimit -c unlimited -S
10 | - mvn -N io.takari:maven:wrapper
11 | - docker run -d -p 127.0.0.1:8500:8500 consul:latest
12 | after_success:
13 | - bash .travis_after_success.sh
14 | cache:
15 | directories:
16 | - $HOME/.m2
17 |
18 | notifications:
19 | email: false
20 |
21 | env:
22 | global:
23 | # CI_DEPLOY_USERNAME
24 | - secure: "Si7FrUAxJ1ZZlYWR9gLQxR3PJ1uCgi5fsw7aPZwA+XVsIkSZ1tGU0AHU3xpfOaXbx01A3EsSOXdDM6Y3MT7NaucL9vo8/cOAoJTAL71SXhUH73FYeHfzlvG7Ok2wf/kqqL9pWIKn2ucpYZiZw8QXYh+xGddbicJmTwH5NA1pZJ4sWUnhpQ6RFTGgJX1xIGWJ+A5Y1u6SHGXLiplPq1uwBpOZOoho8tO7AtGYtCh64Ns6/+wSyx/BFzKkb8jT6IfKZC3ZVLtlb9Y14iwi8L0+oeVIwPtNTymbVP0TH/iwAk9+7mJ3q/sl6Hx5672n2CjyWJVPzyKODs+O0DmVjEclAeiFLr+JJZkldzv9FXmZrt8WnKhHvwtpN5YzMFiD6qExl2cyd6NHSb0qeLzhWvNhSS0kPzalfr2xF7+tiGuDofUu9dOup5mcZYIk2IZtucSwHfRaphZfxvLWeAD5AdI2uSazTOdS/A/kDbwBjYVUxudElIYdZmZFxuxncdizN59ezAFqvj5MJ3EnW2Cv8HtIapnubVqH2fDrvLRYjQCxtnIKih6jMRKACsgIuewZjKcGvhQ7A5fkW9XD0vYYlMuE3b2m7x1MKrjewpeBJNDb10o9/bdytlsjDiJF7wq+en9B5yZJ+V2MxZ0y7/6/JCzb2WMM+KmGiUUrv0ThptE+KGI="
25 | # CI_DEPLOY_PASSWORD
26 | - secure: "Oh4nvjDBbZB4pTQ7eymrCt3BFXCcRt2EZkhq+ornXPwBXG6slALaaXekf2+CItv6U9223zBGFyfX3L7HVCzFO9ViHyUSnMjetcgru+/gQXzX6JBHBIxt/AdO4umoMcbwVzPTAXmZuuAvLyxKUFZdD5WnaJqTTKAkuTx8bsgeO6i3dnGNHg/PPJ+HQO0OU+MlVkIZB//jbV+RRmC8OcSJFNn88lwVdlocsS2i0i9piZ6CHknDYCzFSWoSGzY9U12HUaQeYkQSh8ipndtP9dRjr8fec5kOoyzS1Y7NzhkZ86/DKrm3Upvc16mRl8UWaUX1z9RRLn9WnBhNRezvJxFnKVX9AcufgcancENlrLpJ9ljZxW9O1DJKZtTNblIgWH7HSEzZeh1EE+2icgZQ9+N7Ei7REXSC1es+3ATADtUuol6Jd2VyuEr1d1pFtVKuuFTpMVCNtJxkb8Z0oSyLS0MUopd0JtNVl5pQn0FxwSDnwho6RzIsSLiDZWk1mtNGBA8lXv6RQamBgMBO9m9+dT7PHx7mO3YOc52dukrA0uhsJt7uvQlx/qR8ekHjy8Xq3Ni5lGqhw/rEjZvjZZKZRTvypC9CJi0zDZt8aR1qFlRL8Nb1v09e/qGBT7P6zqw1v8v2Jh+rEZnzcn1fHCmuIt14c3Pr4p3qiP9t0NkmAjcQUug="
27 |
--------------------------------------------------------------------------------
/.travis_after_success.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | if [[ "${TRAVIS_JDK_VERSION}" != "openjdk11" ]]; then
4 | echo "Skipping after_success actions for JDK version \"${TRAVIS_JDK_VERSION}\""
5 | exit
6 | fi
7 |
8 | if [[ -n ${TRAVIS_TAG} ]]; then
9 | echo "Skipping deployment for tag \"${TRAVIS_TAG}\""
10 | exit
11 | fi
12 |
13 | if [[ ${TRAVIS_BRANCH} != 'master' ]]; then
14 | echo "Skipping deployment for branch \"${TRAVIS_BRANCH}\""
15 | exit
16 | fi
17 |
18 | if [[ "$TRAVIS_PULL_REQUEST" = "true" ]]; then
19 | echo "Skipping deployment for pull request"
20 | exit
21 | fi
22 |
23 | ./mvnw -B deploy --settings maven_deploy_settings.xml -Dmaven.test.skip=true
24 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at github@smoketurner.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Guidelines for contributing to dropwizard-consul.
2 |
3 | Please create a pull request against `master`.
4 |
5 | Try to make the code in the pull request as focused and clean as possible. See
6 | our [style guide](http://google.github.io/styleguide/javaguide.html). If the pull
7 | request is too large, we may ask you to split it into smaller ones.
8 |
9 | # License
10 | By contributing your code, you agree to license your contribution under the
11 | terms of the Apache Public License v2:
12 | https://github.com/smoketurner/dropwizard-consul/blob/master/LICENSE
13 |
14 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Dropwizard Consul Bundle
2 | ========================
3 | [](https://travis-ci.org/smoketurner/dropwizard-consul)
4 | [](https://maven-badges.herokuapp.com/maven-central/com.smoketurner.dropwizard/dropwizard-consul/)
5 | [](https://github.com/smoketurner/dropwizard-consul/tree/master)
6 | [](https://www.patreon.com/bePatron?u=9567343)
7 |
8 | A bundle for using [Consul](https://consul.io) in Dropwizard applications. Features:
9 |
10 | * Integrated client-side load balancer based on [Ribbon](https://github.com/netflix/ribbon)
11 | * Dropwizard health check that monitors reachablility of Consul
12 | * The Dropwizard service is registered as a Consul service with a Consul-side health check querying the Dropwizard [health check](https://www.dropwizard.io/en/latest/manual/core.html#health-checks)
13 | * Ability to resolve [configuration](https://www.dropwizard.io/en/latest/manual/core.html#configuration) properties from Consul's KV store
14 | * Admin task to toggle Consul's [maintenance](https://www.consul.io/api/agent.html#enable-maintenance-mode) mode
15 |
16 | Dependency Info
17 | ---------------
18 | ```xml
19 |
20 | com.smoketurner.dropwizard
21 | consul-core
22 | 2.0.7-1
23 |
24 |
25 | com.smoketurner.dropwizard
26 | consul-ribbon
27 | 2.0.7-1
28 |
29 | ```
30 |
31 | Usage
32 | -----
33 | Add a `ConsulBundle` to your [Application](https://javadoc.io/doc/io.dropwizard/dropwizard-project/latest/io/dropwizard/Application.html) class.
34 |
35 | ```java
36 | @Override
37 | public void initialize(Bootstrap bootstrap) {
38 | // ...
39 | bootstrap.addBundle(new ConsulBundle(getName()) {
40 | @Override
41 | public ConsulFactory getConsulFactory(MyConfiguration configuration) {
42 | return configuration.getConsulFactory();
43 | }
44 | });
45 | }
46 | ```
47 |
48 | The bundle also includes a `ConsulSubsitutor` to retrieve configuration values from the Consul KV store. You can define settings in your YAML configuration file:
49 |
50 | ```
51 | template: ${helloworld/template:-Hello, %s!}
52 | defaultName: ${helloworld/defaultName:-Stranger}
53 | ```
54 |
55 | The setting with the path `helloworld/template` will be looked up in the KV store and will be replaced in the configuration file when the application is started. You can specify a default value after the `:-`. This currently does not support dynamically updating values in a running Dropwizard application.
56 |
57 | Configuration
58 | -------------
59 | For configuring the Consul connection, there is a `ConsulFactory`:
60 |
61 | ```yaml
62 | consul:
63 | # Optional properties
64 | # endpoint for consul (defaults to localhost:8500)
65 | endpoint: localhost:8500
66 | # service port
67 | servicePort: 8080
68 | # check interval frequency
69 | checkInterval: 1 second
70 | ```
71 |
72 | Example Application
73 | -------------------
74 | This bundle includes a modified version of the `HelloWorldApplication` from Dropwizard's [Getting Started](https://www.dropwizard.io/1.3.12/docs/getting-started.html) documentation.
75 |
76 | You can execute this application by first starting Consul on your local machine then running:
77 |
78 | ```
79 | mvn clean package
80 | java -jar consul-example/target/consul-example-2.0.7-4-SNAPSHOT.jar server consul-example/hello-world.yml
81 | ```
82 |
83 | This will start the application on port `8080` (admin port `8180`). This application demonstrations the following Consul integration points:
84 |
85 | - The application is registered as a service with Consul (with the [service port](https://www.consul.io/docs/agent/services.html) set to the applicationConnectors port in the configuration file.
86 | - The application will lookup any variables in the configuration file from Consul upon startup (it defaults to connecting to a Consul agent running on `localhost:8500` for this functionality)
87 | - The application exposes an additional HTTP endpoint for querying Consul for available healthy services:
88 | ```
89 | curl -X GET localhost:8080/consul/hello-world -i
90 | HTTP/1.1 200 OK
91 | Date: Mon, 25 Jan 2016 03:42:10 GMT
92 | Content-Type: application/json
93 | Vary: Accept-Encoding
94 | Content-Length: 870
95 |
96 | [
97 | {
98 | "Node": {
99 | "Node": "mac",
100 | "Address": "192.168.1.100",
101 | "Datacenter": "dc1",
102 | "TaggedAddresses": {
103 | "wan": "192.168.1.100",
104 | "lan": "192.168.1.100"
105 | },
106 | "Meta": {
107 | "consul-network-segment": ""
108 | }
109 | },
110 | "Service": {
111 | "ID": "test123",
112 | "Service": "hello-world",
113 | "EnableTagOverride": false,
114 | "Tags": [],
115 | "Address": "",
116 | "Meta": {
117 | "scheme": "http"
118 | },
119 | "Port": 8080,
120 | "Weights": {
121 | "Passing": 1,
122 | "Warning": 1
123 | }
124 | },
125 | "Checks": [
126 | {
127 | "Node": "mac",
128 | "CheckID": "serfHealth",
129 | "Name": "Serf Health Status",
130 | "Status": "passing",
131 | "Notes": "",
132 | "Output": "Agent alive and reachable",
133 | "ServiceID": "",
134 | "ServiceName": "",
135 | "ServiceTags": []
136 | },
137 | {
138 | "Node": "mac",
139 | "CheckID": "service:test123",
140 | "Name": "Service 'hello-world' check",
141 | "Status": "passing",
142 | "Notes": "",
143 | "Output": "HTTP GET http:\/\/127.0.0.1:8180\/healthcheck: 200 OK Output: {\"consul\":{\"healthy\":true},\"deadlocks\":{\"healthy\":true}}",
144 | "ServiceID": "test123",
145 | "ServiceName": "hello-world",
146 | "ServiceTags": []
147 | }
148 | ]
149 | }
150 | ]
151 | ```
152 | - The application will periodically checkin with Consul every second to notify the service check that it is still alive
153 | - Upon shutdown, the application will deregister itself from Consul
154 |
155 | Credits
156 | -------
157 | This bundle was inspired by an older bundle (Dropwizard 0.6.2) that [Chris Gray](https://github.com/chrisgray) created at https://github.com/chrisgray/dropwizard-consul. I also incorporated the configuration provider changes from https://github.com/remmelt/dropwizard-consul-config-provider
158 |
159 | Support
160 | -------
161 | Please file bug reports and feature requests in [GitHub issues](https://github.com/smoketurner/dropwizard-consul/issues).
162 |
163 | License
164 | -------
165 | Copyright (c) 2020 Smoke Turner, LLC
166 |
167 | This library is licensed under the Apache License, Version 2.0.
168 |
169 | See http://www.apache.org/licenses/LICENSE-2.0.html or the [LICENSE](LICENSE) file in this repository for the full license text.
170 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | ## Supported Versions
4 |
5 | Use this section to tell people about which versions of your project are
6 | currently being supported with security updates.
7 |
8 | | Version | Supported |
9 | | ------- | ------------------ |
10 | | < 1.3.0 | :x: |
11 | | 1.3.x | :white_check_mark: |
12 | | 2.0.x | :white_check_mark: |
13 |
14 | ## Reporting a Vulnerability
15 |
16 | Please email any security-related issues or concerns to security@smoketurner.com.
17 | You should expect an email reply within 24-48 hours. If the vulnerability is accepeted,
18 | a new pull request will be created to address the issue and a new patch release
19 | created.
20 |
--------------------------------------------------------------------------------
/consul-core/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/consul-core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
20 | 4.0.0
21 |
22 |
23 | com.smoketurner.dropwizard
24 | dropwizard-consul
25 | 2.0.12-2-SNAPSHOT
26 |
27 |
28 | consul-core
29 | Dropwizard Consul Bundle
30 |
31 |
32 |
33 | io.dropwizard
34 | dropwizard-core
35 |
36 |
37 | com.orbitz.consul
38 | consul-client
39 | 1.5.3
40 |
41 |
42 | commons-net
43 | commons-net
44 | 3.9.0
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/consul-core/src/main/java/com/smoketurner/dropwizard/consul/ConsulBundle.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2019 Smoke Turner, LLC (github@smoketurner.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.smoketurner.dropwizard.consul;
17 |
18 | import com.google.common.annotations.VisibleForTesting;
19 | import com.google.common.base.Strings;
20 | import com.google.common.collect.ImmutableMap;
21 | import com.google.common.net.HostAndPort;
22 | import com.orbitz.consul.Consul;
23 | import com.orbitz.consul.ConsulException;
24 | import com.smoketurner.dropwizard.consul.config.ConsulSubstitutor;
25 | import com.smoketurner.dropwizard.consul.core.ConsulAdvertiser;
26 | import com.smoketurner.dropwizard.consul.core.ConsulServiceListener;
27 | import com.smoketurner.dropwizard.consul.health.ConsulHealthCheck;
28 | import com.smoketurner.dropwizard.consul.managed.ConsulAdvertiserManager;
29 | import com.smoketurner.dropwizard.consul.task.MaintenanceTask;
30 | import io.dropwizard.Configuration;
31 | import io.dropwizard.ConfiguredBundle;
32 | import io.dropwizard.configuration.SubstitutingSourceProvider;
33 | import io.dropwizard.setup.Bootstrap;
34 | import io.dropwizard.setup.Environment;
35 | import io.dropwizard.util.Duration;
36 | import java.util.Objects;
37 | import java.util.Optional;
38 | import java.util.UUID;
39 | import java.util.concurrent.Executors;
40 | import java.util.concurrent.ScheduledExecutorService;
41 | import org.slf4j.Logger;
42 | import org.slf4j.LoggerFactory;
43 |
44 | /**
45 | * Replace variables with values from Consul KV. By default, this only works with a Consul agent
46 | * running on localhost:8500 (the default) as there's no way to configure Consul in the initialize
47 | * methods. You may override {@link #getConsulAgentHost()} and {@link #getConsulAgentPort()} to
48 | * provide other defaults.
49 | *
50 | * @param The configuration class for your Dropwizard Application.
51 | */
52 | public abstract class ConsulBundle
53 | implements ConfiguredBundle, ConsulConfiguration {
54 |
55 | private static final Logger LOGGER = LoggerFactory.getLogger(ConsulBundle.class);
56 | private static final String CONSUL_AUTH_HEADER_KEY = "X-Consul-Token";
57 |
58 | private final String defaultServiceName;
59 | private final boolean strict;
60 | private final boolean substitutionInVariables;
61 |
62 | /**
63 | * Constructor
64 | *
65 | * @param name Service Name
66 | */
67 | public ConsulBundle(final String name) {
68 | this(name, false);
69 | }
70 |
71 | /**
72 | * @param name Service Name
73 | * @param strict If true, the application fails fast if a key cannot be found in Consul KV
74 | */
75 | public ConsulBundle(final String name, final boolean strict) {
76 | this(name, strict, false);
77 | }
78 |
79 | /**
80 | * @param name Service Name
81 | * @param strict If true, the application fails fast if a key cannot be found in Consul KV
82 | * @param substitutionInVariables If true, substitution will be done within variable names.
83 | */
84 | public ConsulBundle(
85 | final String name, final boolean strict, final boolean substitutionInVariables) {
86 | this.defaultServiceName = Objects.requireNonNull(name);
87 | this.strict = strict;
88 | this.substitutionInVariables = substitutionInVariables;
89 | }
90 |
91 | @Override
92 | public void initialize(Bootstrap> bootstrap) {
93 | // Replace variables with values from Consul KV. Please override
94 | // getConsulAgentHost() and getConsulAgentPort() if Consul is not
95 | // listening on the default localhost:8500.
96 | try {
97 | LOGGER.debug("Connecting to Consul at {}:{}", getConsulAgentHost(), getConsulAgentPort());
98 |
99 | final Consul.Builder builder =
100 | Consul.builder()
101 | .withHostAndPort(HostAndPort.fromParts(getConsulAgentHost(), getConsulAgentPort()));
102 |
103 | getConsulAclToken()
104 | .ifPresent(
105 | token -> {
106 | // setting both ACL token here and with header, supplying an
107 | // auth header. This should cover both use cases: endpoint
108 | // supports legacy ?token query param and other case
109 | // in which endpoint requires an X-Consul-Token header.
110 | // @see https://www.consul.io/api/index.html#acls
111 |
112 | LOGGER.debug("Using Consul ACL token: {}", token);
113 |
114 | builder
115 | .withAclToken(token)
116 | .withHeaders(ImmutableMap.of(CONSUL_AUTH_HEADER_KEY, token));
117 | });
118 |
119 | // using Consul as a configuration substitution provider
120 | bootstrap.setConfigurationSourceProvider(
121 | new SubstitutingSourceProvider(
122 | bootstrap.getConfigurationSourceProvider(),
123 | new ConsulSubstitutor(builder.build(), strict, substitutionInVariables)));
124 |
125 | } catch (ConsulException e) {
126 | LOGGER.warn(
127 | "Unable to query Consul running on {}:{}," + " disabling configuration substitution",
128 | getConsulAgentHost(),
129 | getConsulAgentPort(),
130 | e);
131 | }
132 | }
133 |
134 | @Override
135 | public void run(C configuration, Environment environment) throws Exception {
136 | final ConsulFactory consulConfig = getConsulFactory(configuration);
137 | if (!consulConfig.isEnabled()) {
138 | LOGGER.warn("Consul bundle disabled.");
139 | } else {
140 | runEnabled(consulConfig, environment);
141 | }
142 | }
143 |
144 | protected void runEnabled(ConsulFactory consulConfig, Environment environment) {
145 | if (Strings.isNullOrEmpty(consulConfig.getServiceName())) {
146 | consulConfig.setSeviceName(defaultServiceName);
147 | }
148 | setupEnvironment(consulConfig, environment);
149 | }
150 |
151 | protected void setupEnvironment(ConsulFactory consulConfig, Environment environment) {
152 |
153 | final Consul consul = consulConfig.build();
154 | final String serviceId = consulConfig.getServiceId().orElse(UUID.randomUUID().toString());
155 | final ConsulAdvertiser advertiser =
156 | new ConsulAdvertiser(environment, consulConfig, consul, serviceId);
157 |
158 | final Optional retryInterval = consulConfig.getRetryInterval();
159 | final Optional scheduler =
160 | retryInterval.map(i -> Executors.newScheduledThreadPool(1));
161 |
162 | // Register a Jetty listener to get the listening host and port
163 | environment
164 | .lifecycle()
165 | .addServerLifecycleListener(
166 | new ConsulServiceListener(advertiser, retryInterval, scheduler));
167 |
168 | // Register a ping healthcheck to the Consul agent
169 | environment.healthChecks().register("consul", new ConsulHealthCheck(consul));
170 |
171 | // Register a shutdown manager to deregister the service
172 | environment.lifecycle().manage(new ConsulAdvertiserManager(advertiser, scheduler));
173 |
174 | // Add an administrative task to toggle maintenance mode
175 | environment.admin().addTask(new MaintenanceTask(consul, serviceId));
176 | }
177 |
178 | /**
179 | * Override as necessary to provide an alternative Consul Agent Host. This is only required if
180 | * using Consul KV for configuration variable substitution.
181 | *
182 | * @return By default, "localhost"
183 | */
184 | @VisibleForTesting
185 | public String getConsulAgentHost() {
186 | return Consul.DEFAULT_HTTP_HOST;
187 | }
188 |
189 | /**
190 | * Override as necessary to provide an alternative Consul Agent Port. This is only required if
191 | * using Consul KV for configuration variable substitution.
192 | *
193 | * @return By default, 8500
194 | */
195 | @VisibleForTesting
196 | public int getConsulAgentPort() {
197 | return Consul.DEFAULT_HTTP_PORT;
198 | }
199 |
200 | /**
201 | * Override as necessary to provide an alternative ACL Token. This is only required if using
202 | * Consul KV for configuration variable substitution.
203 | *
204 | * @return By default, empty string (no ACL support)
205 | */
206 | @VisibleForTesting
207 | public Optional getConsulAclToken() {
208 | return Optional.empty();
209 | }
210 | }
211 |
--------------------------------------------------------------------------------
/consul-core/src/main/java/com/smoketurner/dropwizard/consul/ConsulConfiguration.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2019 Smoke Turner, LLC (github@smoketurner.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.smoketurner.dropwizard.consul;
17 |
18 | import io.dropwizard.Configuration;
19 |
20 | @FunctionalInterface
21 | public interface ConsulConfiguration {
22 | ConsulFactory getConsulFactory(C configuration);
23 | }
24 |
--------------------------------------------------------------------------------
/consul-core/src/main/java/com/smoketurner/dropwizard/consul/ConsulFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2019 Smoke Turner, LLC (github@smoketurner.com)
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.smoketurner.dropwizard.consul;
17 |
18 | import com.fasterxml.jackson.annotation.JsonIgnore;
19 | import com.fasterxml.jackson.annotation.JsonProperty;
20 | import com.google.common.base.Preconditions;
21 | import com.google.common.collect.ImmutableMap;
22 | import com.google.common.net.HostAndPort;
23 | import com.orbitz.consul.Consul;
24 | import io.dropwizard.util.Duration;
25 | import io.dropwizard.validation.MinDuration;
26 | import java.util.Map;
27 | import java.util.Objects;
28 | import java.util.Optional;
29 | import java.util.concurrent.TimeUnit;
30 | import java.util.function.Supplier;
31 | import javax.annotation.Nullable;
32 | import javax.validation.constraints.NotNull;
33 | import org.apache.commons.net.util.SubnetUtils;
34 |
35 | public class ConsulFactory {
36 | private static final String CONSUL_AUTH_HEADER_KEY = "X-Consul-Token";
37 |
38 | @NotNull
39 | private HostAndPort endpoint =
40 | HostAndPort.fromParts(Consul.DEFAULT_HTTP_HOST, Consul.DEFAULT_HTTP_PORT);
41 |
42 | @Nullable private String serviceName;
43 |
44 | private boolean enabled = true;
45 | private Optional serviceId = Optional.empty();
46 | private Optional servicePort = Optional.empty();
47 | private Optional adminPort = Optional.empty();
48 | private Optional serviceAddress = Optional.empty();
49 | private Optional serviceSubnet = Optional.empty();
50 | private Optional> serviceAddressSupplier = Optional.empty();
51 | private Optional> tags = Optional.empty();
52 | private Optional aclToken = Optional.empty();
53 | private Optional