pax_global_header 0000666 0000000 0000000 00000000064 14420044236 0014511 g ustar 00root root 0000000 0000000 52 comment=40885adbbc0f2e51a41cd9119cad305d9ac32760
curator-apache-curator-5.5.0/ 0000775 0000000 0000000 00000000000 14420044236 0016073 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/.asf.yaml 0000664 0000000 0000000 00000002354 14420044236 0017612 0 ustar 00root root 0000000 0000000 # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
github:
description: "Apache Curator"
homepage: https://curator.apache.org/
labels:
- java
- database
- curator
- zookeeper
- consensus
features:
wiki: false
issues: false
projects: false
enabled_merge_buttons:
squash: true
merge: false
rebase: true
protected_branches:
master: {}
notifications:
commits: commits@curator.apache.org
pullrequests: commits@curator.apache.org
jira_options: link label
curator-apache-curator-5.5.0/.github/ 0000775 0000000 0000000 00000000000 14420044236 0017433 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/.github/workflows/ 0000775 0000000 0000000 00000000000 14420044236 0021470 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/.github/workflows/ci.yml 0000664 0000000 0000000 00000004736 14420044236 0022620 0 ustar 00root root 0000000 0000000 # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
name: CI
on:
push:
branches: [master]
pull_request:
branches: [master]
env:
MAVEN_OPTS: -Dhttp.keepAlive=false -Dmaven.wagon.http.pool=false -Dmaven.wagon.http.retryHandler.class=standard -Dmaven.wagon.http.retryHandler.count=3
jobs:
check:
name: Check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check license header
run: docker run --rm -v $(pwd):/github/workspace -u $(id -u):$(id -g) ghcr.io/korandoru/hawkeye-native:v1 check
unittest:
name: Unit tests
runs-on: ubuntu-latest
timeout-minutes: 120
strategy:
fail-fast: false
matrix:
java: [8, 11]
steps:
- uses: actions/checkout@v3
- name: Cache Local Maven Repository
uses: actions/cache@v3
with:
path: ~/.m2/repository
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Set up JDK ${{ matrix.java }}
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java }}
distribution: 'temurin'
- name: Build with ${{ matrix.java }}
run: ./mvnw clean install -DskipTests
- name: Test with ${{ matrix.java }}
run: ./mvnw verify
required:
name: Required
runs-on: ubuntu-latest
if: ${{ always() }}
needs:
- check
- unittest
steps:
- name: Guardian
run: |
if [[ ! ( \
"${{ needs.check.result }}" == "success" \
&& "${{ needs.unittest.result }}" == "success" \
) ]]; then
echo "Required jobs haven't been completed successfully."
exit -1
fi
curator-apache-curator-5.5.0/.gitignore 0000664 0000000 0000000 00000001375 14420044236 0020071 0 ustar 00root root 0000000 0000000 # Compiled source #
###################
*.com
*.class
*.dll
*.exe
*.o
*.so
# Packages #
############
# it's better to unpack these files and commit the raw source
# git has its own built in compression methods
*.7z
*.dmg
*.gz
*.iso
*.jar
*.rar
*.tar
*.zip
# Logs and databases #
######################
*.log
# OS generated files #
######################
.DS_Store*
ehthumbs.db
Icon?
Thumbs.db
# Editor Files #
################
*~
*.swp
# Gradle Files #
################
.gradle
# Build output directies
/target
*/target
/build
*/build
*/bin
# IntelliJ specific files/directories
out
.idea
*.ipr
*.iws
*.iml
atlassian-ide-plugin.xml
# Eclipse specific files/directories
.classpath
.project
.settings
.metadata
# NetBeans specific files/directories
.nbattrs
curator-apache-curator-5.5.0/.mvn/ 0000775 0000000 0000000 00000000000 14420044236 0016751 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/.mvn/wrapper/ 0000775 0000000 0000000 00000000000 14420044236 0020431 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/.mvn/wrapper/maven-wrapper.properties 0000664 0000000 0000000 00000001773 14420044236 0025343 0 ustar 00root root 0000000 0000000 # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar
curator-apache-curator-5.5.0/DEPENDENCIES 0000664 0000000 0000000 00000000035 14420044236 0017642 0 ustar 00root root 0000000 0000000 * intentionally left blank *
curator-apache-curator-5.5.0/LICENSE 0000664 0000000 0000000 00000026136 14420044236 0017110 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
curator-apache-curator-5.5.0/NOTICE 0000664 0000000 0000000 00000000250 14420044236 0016774 0 ustar 00root root 0000000 0000000 Apache Curator
Copyright 2013-2023 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
curator-apache-curator-5.5.0/README.md 0000664 0000000 0000000 00000004551 14420044236 0017357 0 ustar 00root root 0000000 0000000 # Apache Curator
[](http://search.maven.org/#search%7Cga%7C1%7Capache-curator)
[](https://curator.apache.org)
[](https://stackoverflow.com/questions/tagged/apache-curator)
[](https://twitter.com/intent/follow?original_referer=https%3A%2F%2Fgithub.com%2Fapache%2Fcurator&ref_src=twsrc%5Etfw®ion=follow_link&screen_name=ApacheCurator&tw_p=followbutton)
## What is Apache Curator?
Apache Curator is a Java/JVM client library for [Apache ZooKeeper](https://zookeeper.apache.org/), a distributed coordination service.
Apache Curator includes a high-level API framework and utilities to make using Apache ZooKeeper much easier and more reliable. It also includes recipes for common use cases and extensions such as service discovery and a Java 8 asynchronous DSL.
For more details:
- Apache Curator Website: http://curator.apache.org/
- Binaries on Maven Central: [http://search.maven.org](http://search.maven.org/#search%7Cga%7C1%7Capache-curator)
- Best source of help for Curator: [Stack Overflow's Curator tag](https://stackoverflow.com/questions/tagged/apache-curator)
- Apache ZooKeeper Website: https://zookeeper.apache.org
- Curator's Wiki: http://cwiki.apache.org/confluence/display/CURATOR
curator-apache-curator-5.5.0/curator-client/ 0000775 0000000 0000000 00000000000 14420044236 0021026 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/LICENSE 0000664 0000000 0000000 00000026136 14420044236 0022043 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
curator-apache-curator-5.5.0/curator-client/NOTICE 0000664 0000000 0000000 00000000250 14420044236 0021727 0 ustar 00root root 0000000 0000000 Apache Curator
Copyright 2013-2023 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
curator-apache-curator-5.5.0/curator-client/pom.xml 0000664 0000000 0000000 00000012037 14420044236 0022346 0 ustar 00root root 0000000 0000000
4.0.0org.apache.curatorapache-curator5.5.0curator-client5.5.0bundleCurator ClientLow-level API2011
org.apache.zookeeper.*;version="[3.4,4.0)", *
org.apache.curator.*;version="${project.version}";-noimport:=true
org.apache.zookeeperzookeepercom.google.guavaguavaorg.slf4jslf4j-apiorg.mockitomockito-coretestorg.apache.curatorcurator-testtestorg.junit.jupiterjunit-jupiter-apitestorg.slf4jslf4j-log4j12testorg.awaitilityawaitilitytestorg.assertjassertj-coretestorg.apache.maven.pluginsmaven-shade-pluginapache-curator-guava-shadershadepackagecom.google.guava:guavacom.google.guava:listenablefuturecom.google.guava:failureaccesscom.google.guava:guavaMETA-INF/**org.apache.maven.pluginsmaven-jar-plugintest-jar
curator-apache-curator-5.5.0/curator-client/src/ 0000775 0000000 0000000 00000000000 14420044236 0021615 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/ 0000775 0000000 0000000 00000000000 14420044236 0022541 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/ 0000775 0000000 0000000 00000000000 14420044236 0023462 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/ 0000775 0000000 0000000 00000000000 14420044236 0024251 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/ 0000775 0000000 0000000 00000000000 14420044236 0025472 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ 0000775 0000000 0000000 00000000000 14420044236 0027151 5 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ConnectionState.java 0000664 0000000 0000000 00000024012 14420044236 0033113 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.curator.drivers.EventTrace;
import org.apache.curator.drivers.OperationTrace;
import org.apache.curator.drivers.TracerDriver;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.utils.CloseableUtils;
import org.apache.curator.utils.DebugUtils;
import org.apache.curator.utils.ThreadUtils;
import org.apache.curator.utils.ZookeeperFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
class ConnectionState implements Watcher, Closeable
{
private static final int MAX_BACKGROUND_EXCEPTIONS = 10;
private static final boolean LOG_EVENTS = Boolean.getBoolean(DebugUtils.PROPERTY_LOG_EVENTS);
private static final Logger log = LoggerFactory.getLogger(ConnectionState.class);
private final HandleHolder handleHolder;
private final AtomicBoolean isConnected = new AtomicBoolean(false);
private final AtomicInteger lastNegotiatedSessionTimeoutMs = new AtomicInteger(0);
private final EnsembleProvider ensembleProvider;
private final AtomicReference tracer;
private final Queue backgroundExceptions = new ConcurrentLinkedQueue();
private final Queue parentWatchers = new ConcurrentLinkedQueue();
private final AtomicLong instanceIndex = new AtomicLong();
private volatile long connectionStartMs = 0;
ConnectionState(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, Watcher parentWatcher, AtomicReference tracer, boolean canBeReadOnly)
{
this.ensembleProvider = ensembleProvider;
this.tracer = tracer;
if ( parentWatcher != null )
{
parentWatchers.offer(parentWatcher);
}
handleHolder = new HandleHolder(zookeeperFactory, this, ensembleProvider, sessionTimeoutMs, canBeReadOnly);
}
ZooKeeper getZooKeeper() throws Exception
{
if ( SessionFailRetryLoop.sessionForThreadHasFailed() )
{
throw new SessionFailRetryLoop.SessionFailedException();
}
Exception exception = backgroundExceptions.poll();
if ( exception != null )
{
new EventTrace("background-exceptions", tracer.get()).commit();
throw exception;
}
boolean localIsConnected = isConnected.get();
if ( !localIsConnected )
{
checkNewConnectionString();
}
return handleHolder.getZooKeeper();
}
boolean isConnected()
{
return isConnected.get();
}
void start() throws Exception
{
log.debug("Starting");
ensembleProvider.start();
reset();
}
@Override
public void close() throws IOException {
close(0);
}
public void close(int waitForShutdownTimeoutMs) throws IOException {
log.debug("Closing");
CloseableUtils.closeQuietly(ensembleProvider);
try
{
handleHolder.closeAndClear(waitForShutdownTimeoutMs);
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
throw new IOException(e);
}
finally
{
isConnected.set(false);
}
}
void addParentWatcher(Watcher watcher)
{
parentWatchers.offer(watcher);
}
void removeParentWatcher(Watcher watcher)
{
parentWatchers.remove(watcher);
}
long getInstanceIndex()
{
return instanceIndex.get();
}
int getLastNegotiatedSessionTimeoutMs()
{
return lastNegotiatedSessionTimeoutMs.get();
}
@Override
public void process(WatchedEvent event)
{
if ( LOG_EVENTS )
{
log.debug("ConnectState watcher: " + event);
}
if ( event.getType() == Watcher.Event.EventType.None )
{
boolean wasConnected = isConnected.get();
boolean newIsConnected = checkState(event.getState(), wasConnected);
if ( newIsConnected != wasConnected )
{
isConnected.set(newIsConnected);
connectionStartMs = System.currentTimeMillis();
if ( newIsConnected )
{
lastNegotiatedSessionTimeoutMs.set(handleHolder.getNegotiatedSessionTimeoutMs());
log.debug("Negotiated session timeout: " + lastNegotiatedSessionTimeoutMs.get());
}
}
}
for ( Watcher parentWatcher : parentWatchers )
{
OperationTrace trace = new OperationTrace("connection-state-parent-process", tracer.get(), getSessionId());
parentWatcher.process(event);
trace.commit();
}
}
EnsembleProvider getEnsembleProvider()
{
return ensembleProvider;
}
synchronized void reset() throws Exception
{
log.debug("reset");
instanceIndex.incrementAndGet();
isConnected.set(false);
connectionStartMs = System.currentTimeMillis();
handleHolder.closeAndReset();
handleHolder.getZooKeeper(); // initiate connection
}
private synchronized void checkNewConnectionString()
{
final String newConnectionString = handleHolder.getNewConnectionString();
if (newConnectionString != null)
{
handleNewConnectionString(newConnectionString);
}
}
/**
* Return the current session id
*/
public long getSessionId() {
long sessionId = 0;
try {
ZooKeeper zk = handleHolder.getZooKeeper();
if (zk != null) {
sessionId = zk.getSessionId();
}
} catch (Exception e) {
// Ignore the exception
}
return sessionId;
}
private boolean checkState(Event.KeeperState state, boolean wasConnected)
{
boolean isConnected = wasConnected;
boolean checkNewConnectionString = true;
switch ( state )
{
default:
case Disconnected:
{
isConnected = false;
break;
}
case SyncConnected:
case ConnectedReadOnly:
{
isConnected = true;
break;
}
case AuthFailed:
{
isConnected = false;
log.error("Authentication failed");
break;
}
case Expired:
{
isConnected = false;
checkNewConnectionString = false;
handleExpiredSession();
break;
}
case SaslAuthenticated:
{
// NOP
break;
}
}
// the session expired is logged in handleExpiredSession, so not log here
if (state != Event.KeeperState.Expired) {
new EventTrace(state.toString(), tracer.get(), getSessionId()).commit();
}
if ( checkNewConnectionString )
{
String newConnectionString = handleHolder.getNewConnectionString();
if ( newConnectionString != null )
{
handleNewConnectionString(newConnectionString);
}
}
return isConnected;
}
private void handleNewConnectionString(String newConnectionString)
{
log.info("Connection string changed to: " + newConnectionString);
new EventTrace("connection-string-changed", tracer.get(), getSessionId()).commit();
try
{
ZooKeeper zooKeeper = handleHolder.getZooKeeper();
if ( zooKeeper == null )
{
log.warn("Could not update the connection string because getZooKeeper() returned null.");
}
else
{
if ( ensembleProvider.updateServerListEnabled() )
{
zooKeeper.updateServerList(newConnectionString);
handleHolder.resetConnectionString(newConnectionString);
}
else
{
reset();
}
}
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
queueBackgroundException(e);
}
}
private void handleExpiredSession()
{
log.warn("Session expired event received");
new EventTrace("session-expired", tracer.get(), getSessionId()).commit();
try
{
reset();
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
queueBackgroundException(e);
}
}
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
private void queueBackgroundException(Exception e)
{
while ( backgroundExceptions.size() >= MAX_BACKGROUND_EXCEPTIONS )
{
backgroundExceptions.poll();
}
backgroundExceptions.offer(e);
}
}
CuratorConnectionLossException.java 0000664 0000000 0000000 00000002007 14420044236 0036113 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.zookeeper.KeeperException;
public class CuratorConnectionLossException extends KeeperException.ConnectionLossException
{
private static final long serialVersionUID = 1L;
}
CuratorZookeeperClient.java 0000664 0000000 0000000 00000032434 14420044236 0034405 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import com.google.common.base.Preconditions;
import org.apache.curator.drivers.OperationTrace;
import org.apache.curator.drivers.TracerDriver;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.ensemble.fixed.FixedEnsembleProvider;
import org.apache.curator.utils.DefaultTracerDriver;
import org.apache.curator.utils.DefaultZookeeperFactory;
import org.apache.curator.utils.ThreadUtils;
import org.apache.curator.utils.ZookeeperFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* A wrapper around Zookeeper that takes care of some low-level housekeeping
*/
@SuppressWarnings("UnusedDeclaration")
public class CuratorZookeeperClient implements Closeable
{
private final Logger log = LoggerFactory.getLogger(getClass());
private final ConnectionState state;
private final AtomicReference retryPolicy = new AtomicReference();
private final int connectionTimeoutMs;
private final int waitForShutdownTimeoutMs;
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicReference tracer = new AtomicReference(new DefaultTracerDriver());
/**
*
* @param connectString list of servers to connect to
* @param sessionTimeoutMs session timeout
* @param connectionTimeoutMs connection timeout
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
*/
public CuratorZookeeperClient(String connectString, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy)
{
this(new DefaultZookeeperFactory(), new FixedEnsembleProvider(connectString), sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false);
}
/**
* @param ensembleProvider the ensemble provider
* @param sessionTimeoutMs session timeout
* @param connectionTimeoutMs connection timeout
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
*/
public CuratorZookeeperClient(EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy)
{
this(new DefaultZookeeperFactory(), ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, watcher, retryPolicy, false);
}
/**
* @param zookeeperFactory factory for creating {@link ZooKeeper} instances
* @param ensembleProvider the ensemble provider
* @param sessionTimeoutMs session timeout
* @param connectionTimeoutMs connection timeout
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
* @param canBeReadOnly if true, allow ZooKeeper client to enter
* read only mode in case of a network partition. See
* {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)}
* for details
*/
public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider, int sessionTimeoutMs, int connectionTimeoutMs, Watcher watcher, RetryPolicy retryPolicy, boolean canBeReadOnly)
{
this(zookeeperFactory, ensembleProvider, sessionTimeoutMs, connectionTimeoutMs, 0, watcher, retryPolicy, canBeReadOnly);
}
/**
* @param zookeeperFactory factory for creating {@link ZooKeeper} instances
* @param ensembleProvider the ensemble provider
* @param sessionTimeoutMs session timeout
* @param connectionTimeoutMs connection timeout
* @param waitForShutdownTimeoutMs default timeout fo close operation
* @param watcher default watcher or null
* @param retryPolicy the retry policy to use
* @param canBeReadOnly if true, allow ZooKeeper client to enter
* read only mode in case of a network partition. See
* {@link ZooKeeper#ZooKeeper(String, int, Watcher, long, byte[], boolean)}
* for details
* @since 4.0.2
*/
public CuratorZookeeperClient(ZookeeperFactory zookeeperFactory, EnsembleProvider ensembleProvider,
int sessionTimeoutMs, int connectionTimeoutMs, int waitForShutdownTimeoutMs, Watcher watcher,
RetryPolicy retryPolicy, boolean canBeReadOnly)
{
if ( sessionTimeoutMs < connectionTimeoutMs )
{
log.warn(String.format("session timeout [%d] is less than connection timeout [%d]", sessionTimeoutMs, connectionTimeoutMs));
}
retryPolicy = Preconditions.checkNotNull(retryPolicy, "retryPolicy cannot be null");
ensembleProvider = Preconditions.checkNotNull(ensembleProvider, "ensembleProvider cannot be null");
this.connectionTimeoutMs = connectionTimeoutMs;
this.waitForShutdownTimeoutMs = waitForShutdownTimeoutMs;
state = new ConnectionState(zookeeperFactory, ensembleProvider, sessionTimeoutMs, watcher, tracer, canBeReadOnly);
setRetryPolicy(retryPolicy);
}
/**
* Return the managed ZK instance.
*
* @return client the client
* @throws Exception if the connection timeout has elapsed or an exception occurs in a background process
*/
public ZooKeeper getZooKeeper() throws Exception
{
Preconditions.checkState(started.get(), "Client is not started");
return state.getZooKeeper();
}
/**
* Return a new retry loop. All operations should be performed in a retry loop
*
* @return new retry loop
*/
public RetryLoop newRetryLoop()
{
return new RetryLoopImpl(retryPolicy.get(), tracer);
}
/**
* Return a new "session fail" retry loop. See {@link SessionFailRetryLoop} for details
* on when to use it.
*
* @param mode failure mode
* @return new retry loop
*/
public SessionFailRetryLoop newSessionFailRetryLoop(SessionFailRetryLoop.Mode mode)
{
return new SessionFailRetryLoop(this, mode);
}
/**
* Returns true if the client is current connected
*
* @return true/false
*/
public boolean isConnected()
{
return state.isConnected();
}
/**
* This method blocks until the connection to ZK succeeds. Use with caution. The block
* will timeout after the connection timeout (as passed to the constructor) has elapsed
*
* @return true if the connection succeeded, false if not
* @throws InterruptedException interrupted while waiting
*/
public boolean blockUntilConnectedOrTimedOut() throws InterruptedException
{
Preconditions.checkState(started.get(), "Client is not started");
log.debug("blockUntilConnectedOrTimedOut() start");
OperationTrace trace = startAdvancedTracer("blockUntilConnectedOrTimedOut");
internalBlockUntilConnectedOrTimedOut();
trace.commit();
boolean localIsConnected = state.isConnected();
log.debug("blockUntilConnectedOrTimedOut() end. isConnected: " + localIsConnected);
return localIsConnected;
}
/**
* Must be called after construction
*
* @throws IOException errors
*/
public void start() throws Exception
{
log.debug("Starting");
if ( !started.compareAndSet(false, true) )
{
throw new IllegalStateException("Already started");
}
state.start();
}
/**
* Close the client.
*
* Same as {@link #close(int) } using the timeout set at construction time.
*
* @see #close(int)
*/
@Override
public void close() {
close(waitForShutdownTimeoutMs);
}
/**
* Close this client object as the {@link #close() } method.
* This method will wait for internal resources to be released.
*
* @param waitForShutdownTimeoutMs timeout (in milliseconds) to wait for resources to be released.
* Use zero or a negative value to skip the wait.
*/
public void close(int waitForShutdownTimeoutMs)
{
log.debug("Closing, waitForShutdownTimeoutMs {}", waitForShutdownTimeoutMs);
started.set(false);
try
{
state.close(waitForShutdownTimeoutMs);
}
catch ( IOException e )
{
ThreadUtils.checkInterrupted(e);
log.error("", e);
}
}
/**
* Change the retry policy
*
* @param policy new policy
*/
public void setRetryPolicy(RetryPolicy policy)
{
Preconditions.checkNotNull(policy, "policy cannot be null");
retryPolicy.set(policy);
}
/**
* Return the current retry policy
*
* @return policy
*/
public RetryPolicy getRetryPolicy()
{
return retryPolicy.get();
}
/**
* Start a new tracer
* @param name name of the event
* @return the new tracer ({@link TimeTrace#commit()} must be called)
*/
public TimeTrace startTracer(String name)
{
return new TimeTrace(name, tracer.get());
}
/**
* Start a new advanced tracer with more metrics being recorded
* @param name name of the event
* @return the new tracer ({@link OperationTrace#commit()} must be called)
*/
public OperationTrace startAdvancedTracer(String name)
{
return new OperationTrace(name, tracer.get(), state.getSessionId());
}
/**
* Return the current tracing driver
*
* @return tracing driver
*/
public TracerDriver getTracerDriver()
{
return tracer.get();
}
/**
* Change the tracing driver
*
* @param tracer new tracing driver
*/
public void setTracerDriver(TracerDriver tracer)
{
this.tracer.set(tracer);
}
/**
* Returns the current known connection string - not guaranteed to be correct
* value at any point in the future.
*
* @return connection string
*/
public String getCurrentConnectionString()
{
return state.getEnsembleProvider().getConnectionString();
}
/**
* Return the configured connection timeout
*
* @return timeout
*/
public int getConnectionTimeoutMs()
{
return connectionTimeoutMs;
}
/**
* For internal use only - reset the internally managed ZK handle
*
* @throws Exception errors
*/
public void reset() throws Exception
{
state.reset();
}
/**
* Every time a new {@link ZooKeeper} instance is allocated, the "instance index"
* is incremented.
*
* @return the current instance index
*/
public long getInstanceIndex()
{
return state.getInstanceIndex();
}
/**
* Return the most recent value of {@link ZooKeeper#getSessionTimeout()} or 0
*
* @return session timeout or 0
*/
public int getLastNegotiatedSessionTimeoutMs()
{
return state.getLastNegotiatedSessionTimeoutMs();
}
void addParentWatcher(Watcher watcher)
{
state.addParentWatcher(watcher);
}
void removeParentWatcher(Watcher watcher)
{
state.removeParentWatcher(watcher);
}
/**
* For internal use only
*
* @throws InterruptedException interruptions
*/
public void internalBlockUntilConnectedOrTimedOut() throws InterruptedException
{
long waitTimeMs = connectionTimeoutMs;
while ( !state.isConnected() && (waitTimeMs > 0) )
{
final CountDownLatch latch = new CountDownLatch(1);
Watcher tempWatcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
latch.countDown();
}
};
state.addParentWatcher(tempWatcher);
long startTimeMs = System.currentTimeMillis();
long timeoutMs = Math.min(waitTimeMs, 1000);
try
{
latch.await(timeoutMs, TimeUnit.MILLISECONDS);
}
finally
{
state.removeParentWatcher(tempWatcher);
}
long elapsed = Math.max(1, System.currentTimeMillis() - startTimeMs);
waitTimeMs -= elapsed;
}
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/HandleHolder.java 0000664 0000000 0000000 00000011554 14420044236 0032353 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.curator.utils.ZookeeperFactory;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
class HandleHolder
{
private final ZookeeperFactory zookeeperFactory;
private final Watcher watcher;
private final EnsembleProvider ensembleProvider;
private final int sessionTimeout;
private final boolean canBeReadOnly;
private volatile Helper helper;
HandleHolder(ZookeeperFactory zookeeperFactory, Watcher watcher, EnsembleProvider ensembleProvider, int sessionTimeout, boolean canBeReadOnly)
{
this.zookeeperFactory = zookeeperFactory;
this.watcher = watcher;
this.ensembleProvider = ensembleProvider;
this.sessionTimeout = sessionTimeout;
this.canBeReadOnly = canBeReadOnly;
}
ZooKeeper getZooKeeper() throws Exception
{
return (helper != null) ? helper.getZooKeeper() : null;
}
int getNegotiatedSessionTimeoutMs()
{
return (helper != null) ? helper.getNegotiatedSessionTimeoutMs() : 0;
}
String getConnectionString()
{
return (helper != null) ? helper.getConnectionString() : null;
}
String getNewConnectionString()
{
String helperConnectionString = (helper != null) ? helper.getConnectionString() : null;
String ensembleProviderConnectionString = ensembleProvider.getConnectionString();
return ((helperConnectionString != null) && !ensembleProviderConnectionString.equals(helperConnectionString)) ? ensembleProviderConnectionString : null;
}
void resetConnectionString(String connectionString)
{
if ( helper != null )
{
helper.resetConnectionString(connectionString);
}
}
void closeAndClear(int waitForShutdownTimeoutMs) throws Exception
{
internalClose(waitForShutdownTimeoutMs);
helper = null;
}
void closeAndReset() throws Exception
{
internalClose(0);
Helper.Data data = new Helper.Data(); // data shared between initial Helper and the un-synchronized Helper
// first helper is synchronized when getZooKeeper is called. Subsequent calls
// are not synchronized.
//noinspection NonAtomicOperationOnVolatileField
helper = new Helper(data)
{
@Override
ZooKeeper getZooKeeper() throws Exception
{
synchronized(this)
{
if ( data.zooKeeperHandle == null )
{
resetConnectionString(ensembleProvider.getConnectionString());
data.zooKeeperHandle = zookeeperFactory.newZooKeeper(data.connectionString, sessionTimeout, watcher, canBeReadOnly);
}
helper = new Helper(data);
return super.getZooKeeper();
}
}
};
}
private void internalClose(int waitForShutdownTimeoutMs) throws Exception
{
try
{
ZooKeeper zooKeeper = (helper != null) ? helper.getZooKeeper() : null;
if ( zooKeeper != null )
{
Watcher dummyWatcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
}
};
zooKeeper.register(dummyWatcher); // clear the default watcher so that no new events get processed by mistake
if ( waitForShutdownTimeoutMs == 0 )
{
zooKeeper.close(); // coming from closeAndReset() which is executed in ZK's event thread. Cannot use zooKeeper.close(n) otherwise we'd get a dead lock
}
else
{
zooKeeper.close(waitForShutdownTimeoutMs);
}
}
}
catch ( InterruptedException dummy )
{
Thread.currentThread().interrupt();
}
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/Helper.java 0000664 0000000 0000000 00000003036 14420044236 0031235 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.zookeeper.ZooKeeper;
class Helper
{
private final Data data;
static class Data
{
volatile ZooKeeper zooKeeperHandle = null;
volatile String connectionString = null;
}
Helper(Data data)
{
this.data = data;
}
ZooKeeper getZooKeeper() throws Exception
{
return data.zooKeeperHandle;
}
String getConnectionString()
{
return data.connectionString;
}
int getNegotiatedSessionTimeoutMs()
{
return (data.zooKeeperHandle != null) ? data.zooKeeperHandle.getSessionTimeout() : 0;
}
void resetConnectionString(String connectionString)
{
data.connectionString = connectionString;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/RetryLoop.java 0000664 0000000 0000000 00000007677 14420044236 0031774 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.curator.connection.ThreadLocalRetryLoop;
import org.apache.curator.utils.ThreadUtils;
import java.util.concurrent.Callable;
/**
*
Mechanism to perform an operation on Zookeeper that is safe against
* disconnections and "recoverable" errors.
*
*
* If an exception occurs during the operation, the RetryLoop will process it,
* check with the current retry policy and either attempt to reconnect or re-throw
* the exception
*
*
* Canonical usage:
*
* RetryLoop retryLoop = client.newRetryLoop();
* while ( retryLoop.shouldContinue() )
* {
* try
* {
* // do your work
* ZooKeeper zk = client.getZooKeeper(); // it's important to re-get the ZK instance in case there was an error and the instance was re-created
*
* retryLoop.markComplete();
* }
* catch ( Exception e )
* {
* retryLoop.takeException(e);
* }
* }
*
*
*
* Note: this an {@code abstract class} instead of an {@code interface} for historical reasons. It was originally a class
* and if it becomes an interface we risk {@link java.lang.IncompatibleClassChangeError}s with clients.
*
*/
public abstract class RetryLoop
{
/**
* Returns the default retry sleeper
*
* @return sleeper
*/
public static RetrySleeper getDefaultRetrySleeper()
{
return RetryLoopImpl.getRetrySleeper();
}
/**
* Convenience utility: creates a retry loop calling the given proc and retrying if needed
*
* @param client Zookeeper
* @param proc procedure to call with retry
* @param return type
* @return procedure result
* @throws Exception any non-retriable errors
*/
public static T callWithRetry(CuratorZookeeperClient client, Callable proc) throws Exception
{
client.internalBlockUntilConnectedOrTimedOut();
T result = null;
ThreadLocalRetryLoop threadLocalRetryLoop = new ThreadLocalRetryLoop();
RetryLoop retryLoop = threadLocalRetryLoop.getRetryLoop(client::newRetryLoop);
try
{
while ( retryLoop.shouldContinue() )
{
try
{
result = proc.call();
retryLoop.markComplete();
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
}
finally
{
threadLocalRetryLoop.release();
}
return result;
}
/**
* If true is returned, make an attempt at the operation
*
* @return true/false
*/
public abstract boolean shouldContinue();
/**
* Call this when your operation has successfully completed
*/
public abstract void markComplete();
/**
* Pass any caught exceptions here
*
* @param exception the exception
* @throws Exception if not retry-able or the retry policy returned negative
*/
public abstract void takeException(Exception exception) throws Exception;
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/RetryLoopImpl.java 0000664 0000000 0000000 00000006055 14420044236 0032603 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.curator.drivers.EventTrace;
import org.apache.curator.drivers.TracerDriver;
import org.apache.curator.utils.DebugUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.atomic.AtomicReference;
class RetryLoopImpl extends RetryLoop
{
private boolean isDone = false;
private int retryCount = 0;
private final Logger log = LoggerFactory.getLogger(getClass());
private final long startTimeMs = System.currentTimeMillis();
private final RetryPolicy retryPolicy;
private final AtomicReference tracer;
private static final RetrySleeper sleeper = (time, unit) -> unit.sleep(time);
RetryLoopImpl(RetryPolicy retryPolicy, AtomicReference tracer)
{
this.retryPolicy = retryPolicy;
this.tracer = tracer;
}
static RetrySleeper getRetrySleeper()
{
return sleeper;
}
@Override
public boolean shouldContinue()
{
return !isDone;
}
@Override
public void markComplete()
{
isDone = true;
}
@Override
public void takeException(Exception exception) throws Exception
{
boolean rethrow = true;
if ( retryPolicy.allowRetry(exception) )
{
if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
{
log.debug("Retry-able exception received", exception);
}
if ( retryPolicy.allowRetry(retryCount++, System.currentTimeMillis() - startTimeMs, sleeper) )
{
new EventTrace("retries-allowed", tracer.get()).commit();
if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
{
log.debug("Retrying operation");
}
rethrow = false;
}
else
{
new EventTrace("retries-disallowed", tracer.get()).commit();
if ( !Boolean.getBoolean(DebugUtils.PROPERTY_DONT_LOG_CONNECTION_ISSUES) )
{
log.debug("Retry policy not allowing retry");
}
}
}
if ( rethrow )
{
throw exception;
}
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/RetryPolicy.java 0000664 0000000 0000000 00000004324 14420044236 0032304 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.zookeeper.KeeperException;
/**
* Abstracts the policy to use when retrying connections
*/
public interface RetryPolicy
{
/**
* Called when an operation has failed for some reason. This method should return
* true to make another attempt.
*
*
* @param retryCount the number of times retried so far (0 the first time)
* @param elapsedTimeMs the elapsed time in ms since the operation was attempted
* @param sleeper use this to sleep - DO NOT call Thread.sleep
* @return true/false
*/
boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper);
/**
* Called when an operation has failed with a specific exception. This method
* should return true to make another attempt.
*
* @param exception the cause that this operation failed
* @return true/false
*/
default boolean allowRetry(Throwable exception)
{
if ( exception instanceof KeeperException)
{
final int rc = ((KeeperException) exception).code().intValue();
return (rc == KeeperException.Code.CONNECTIONLOSS.intValue()) ||
(rc == KeeperException.Code.OPERATIONTIMEOUT.intValue()) ||
(rc == KeeperException.Code.SESSIONMOVED.intValue()) ||
(rc == KeeperException.Code.SESSIONEXPIRED.intValue());
}
return false;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/RetrySleeper.java 0000664 0000000 0000000 00000002302 14420044236 0032436 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import java.util.concurrent.TimeUnit;
/**
* Abstraction for retry policies to sleep
*/
public interface RetrySleeper
{
/**
* Sleep for the given time
*
* @param time time
* @param unit time unit
* @throws InterruptedException if the sleep is interrupted
*/
public void sleepFor(long time, TimeUnit unit) throws InterruptedException;
}
SessionFailRetryLoop.java 0000664 0000000 0000000 00000020044 14420044236 0034034 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.curator.utils.ThreadUtils;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import java.io.Closeable;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicBoolean;
/**
*
* See {@link RetryLoop} for the main details on retry loops. All Curator/ZooKeeper operations
* should be done in a retry loop.
*
*
*
* The standard retry loop treats session failure as a type of connection failure. i.e. the fact
* that it is a session failure isn't considered. This can be problematic if you are performing
* a series of operations that rely on ephemeral nodes. If the session fails after the ephemeral
* node has been created, future Curator/ZooKeeper operations may succeed even though the
* ephemeral node has been removed by ZooKeeper.
*
*
*
* Here's an example:
*
*
*
You create an ephemeral/sequential node as a kind of lock/marker
*
You perform some other operations
*
The session fails for some reason
*
You attempt to create a node assuming that the lock/marker still exists
*
*
Curator will notice the session failure and try to reconnect
*
In most cases, the reconnect will succeed and, thus, the node creation will succeed
* even though the ephemeral node will have been deleted by ZooKeeper.
*
*
*
*
*
* The SessionFailRetryLoop prevents this type of scenario. When a session failure is detected,
* the thread is marked as failed which will cause all future Curator operations to fail. The
* SessionFailRetryLoop will then either retry the entire
* set of operations or fail (depending on {@link SessionFailRetryLoop.Mode})
*
*/
public class SessionFailRetryLoop implements Closeable
{
private final CuratorZookeeperClient client;
private final Mode mode;
private final Thread ourThread = Thread.currentThread();
private final AtomicBoolean sessionHasFailed = new AtomicBoolean(false);
private final AtomicBoolean isDone = new AtomicBoolean(false);
private final RetryLoop retryLoop;
private final Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
if ( event.getState() == Event.KeeperState.Expired )
{
sessionHasFailed.set(true);
failedSessionThreads.add(ourThread);
}
}
};
private static final Set failedSessionThreads = Sets.newSetFromMap(Maps.newConcurrentMap());
public static class SessionFailedException extends Exception
{
private static final long serialVersionUID = 1L;
}
public enum Mode
{
/**
* If the session fails, retry the entire set of operations when {@link SessionFailRetryLoop#shouldContinue()}
* is called
*/
RETRY,
/**
* If the session fails, throw {@link KeeperException.SessionExpiredException} when
* {@link SessionFailRetryLoop#shouldContinue()} is called
*/
FAIL
}
/**
* Convenience utility: creates a "session fail" retry loop calling the given proc
*
* @param client Zookeeper
* @param mode how to handle session failures
* @param proc procedure to call with retry
* @param return type
* @return procedure result
* @throws Exception any non-retriable errors
*/
public static T callWithRetry(CuratorZookeeperClient client, Mode mode, Callable proc) throws Exception
{
T result = null;
SessionFailRetryLoop retryLoop = client.newSessionFailRetryLoop(mode);
retryLoop.start();
try
{
while ( retryLoop.shouldContinue() )
{
try
{
result = proc.call();
}
catch ( Exception e )
{
ThreadUtils.checkInterrupted(e);
retryLoop.takeException(e);
}
}
}
finally
{
retryLoop.close();
}
return result;
}
SessionFailRetryLoop(CuratorZookeeperClient client, Mode mode)
{
this.client = client;
this.mode = mode;
retryLoop = client.newRetryLoop();
}
static boolean sessionForThreadHasFailed()
{
return failedSessionThreads.contains(Thread.currentThread());
}
/**
* SessionFailRetryLoop must be started
*/
public void start()
{
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
client.addParentWatcher(watcher);
}
/**
* If true is returned, make an attempt at the set of operations
*
* @return true/false
*/
public boolean shouldContinue()
{
boolean localIsDone = isDone.getAndSet(true);
return !localIsDone;
}
/**
* Must be called in a finally handler when done with the loop
*/
@Override
public void close()
{
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
failedSessionThreads.remove(ourThread);
client.removeParentWatcher(watcher);
}
/**
* Pass any caught exceptions here
*
* @param exception the exception
* @throws Exception if not retry-able or the retry policy returned negative
*/
public void takeException(Exception exception) throws Exception
{
Preconditions.checkState(Thread.currentThread().equals(ourThread), "Not in the correct thread");
boolean passUp = true;
if ( sessionHasFailed.get() )
{
switch ( mode )
{
case RETRY:
{
sessionHasFailed.set(false);
failedSessionThreads.remove(ourThread);
if ( exception instanceof SessionFailedException )
{
isDone.set(false);
passUp = false;
}
break;
}
case FAIL:
{
break;
}
}
}
if ( passUp )
{
retryLoop.takeException(exception);
}
}
}
SessionFailedRetryPolicy.java 0000664 0000000 0000000 00000003220 14420044236 0034670 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.zookeeper.KeeperException;
/**
* {@link RetryPolicy} implementation that failed on session expired.
*/
public class SessionFailedRetryPolicy implements RetryPolicy
{
private final RetryPolicy delegatePolicy;
public SessionFailedRetryPolicy(RetryPolicy delegatePolicy)
{
this.delegatePolicy = delegatePolicy;
}
@Override
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
{
return delegatePolicy.allowRetry(retryCount, elapsedTimeMs, sleeper);
}
@Override
public boolean allowRetry(Throwable exception)
{
if ( exception instanceof KeeperException.SessionExpiredException )
{
return false;
}
else
{
return delegatePolicy.allowRetry(exception);
}
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/TimeTrace.java 0000664 0000000 0000000 00000003071 14420044236 0031672 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator;
import org.apache.curator.drivers.TracerDriver;
import java.util.concurrent.TimeUnit;
/**
* Utility to time a method or portion of code
*/
public class TimeTrace
{
private final String name;
private final TracerDriver driver;
private final long startTimeNanos = System.nanoTime();
/**
* Create and start a timer
*
* @param name name of the event
* @param driver driver
*/
public TimeTrace(String name, TracerDriver driver)
{
this.name = name;
this.driver = driver;
}
/**
* Record the elapsed time
*/
public void commit()
{
long elapsed = System.nanoTime() - startTimeNanos;
driver.addTrace(name, elapsed, TimeUnit.NANOSECONDS);
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/connection/ 0000775 0000000 0000000 00000000000 14420044236 0031310 5 ustar 00root root 0000000 0000000 ThreadLocalRetryLoop.java 0000664 0000000 0000000 00000011253 14420044236 0036140 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/connection /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.connection;
import org.apache.curator.RetryLoop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Objects;
import java.util.function.Supplier;
/**
*
* Retry loops can easily end up getting nested which can cause exponential calls of the retry policy
* (see https://issues.apache.org/jira/browse/CURATOR-559). This utility works around that by using
* an internal ThreadLocal to hold a retry loop. E.g. if the retry loop fails anywhere in the chain
* of nested calls it will fail for the rest of the nested calls instead.
*
*/
public class ThreadLocalRetryLoop
{
private static final Logger log = LoggerFactory.getLogger(ThreadLocalRetryLoop.class);
private static final ThreadLocal threadLocal = new ThreadLocal<>();
private static class Entry
{
private final RetryLoop retryLoop;
private int counter;
Entry(RetryLoop retryLoop)
{
this.retryLoop = retryLoop;
}
}
private static class WrappedRetryLoop extends RetryLoop
{
private final RetryLoop retryLoop;
private Exception takenException;
public WrappedRetryLoop(RetryLoop retryLoop)
{
this.retryLoop = retryLoop;
}
@Override
public boolean shouldContinue()
{
return retryLoop.shouldContinue() && (takenException == null);
}
@Override
public void markComplete()
{
retryLoop.markComplete();
}
@Override
public void takeException(Exception exception) throws Exception
{
if ( takenException != null )
{
if ( exception.getClass() != takenException.getClass() )
{
log.error("Multiple exceptions in retry loop", exception);
}
throw takenException;
}
try
{
retryLoop.takeException(exception);
}
catch ( Exception e )
{
takenException = e;
throw e;
}
}
}
/**
* Call to get the current retry loop. If there isn't one, one is allocated
* via {@code newRetryLoopSupplier}.
*
* @param newRetryLoopSupplier supply a new retry loop when needed. Normally you should use {@link org.apache.curator.CuratorZookeeperClient#newRetryLoop()}
* @return retry loop to use
*/
public RetryLoop getRetryLoop(Supplier newRetryLoopSupplier)
{
Entry entry = threadLocal.get();
if ( entry == null )
{
entry = new Entry(new WrappedRetryLoop(newRetryLoopSupplier.get()));
threadLocal.set(entry);
}
++entry.counter;
return entry.retryLoop;
}
/**
* Must be called to release the retry loop. See {@link RetryLoop#callWithRetry(org.apache.curator.CuratorZookeeperClient, java.util.concurrent.Callable)}
* for an example usage.
*/
public void release()
{
Entry entry = Objects.requireNonNull(threadLocal.get(), "No retry loop was set - unbalanced call to release()");
if ( --entry.counter <= 0 )
{
threadLocal.remove();
}
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/drivers/ 0000775 0000000 0000000 00000000000 14420044236 0030627 5 ustar 00root root 0000000 0000000 AdvancedTracerDriver.java 0000664 0000000 0000000 00000003062 14420044236 0035436 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/drivers /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.drivers;
import java.util.concurrent.TimeUnit;
/**
* Expose more metrics for the operations and events
*/
public abstract class AdvancedTracerDriver implements TracerDriver
{
/**
* Record the given trace event
*
* @param trace the metrics of the operation
*/
public abstract void addTrace(OperationTrace trace);
/**
* Add to a named counter
*
* @param name name of the counter
* @param increment amount to increment
*/
public abstract void addEvent(EventTrace trace);
@Deprecated
@Override
public final void addTrace(String name, long time, TimeUnit unit) {}
@Deprecated
@Override
public final void addCount(String name, int increment) {}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/drivers/EventTrace.java0000664 0000000 0000000 00000003006 14420044236 0033531 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.drivers;
public class EventTrace
{
private final String name;
private final TracerDriver driver;
private final long sessionId;
public EventTrace(String name, TracerDriver driver) {
this(name, driver, -1);
}
public EventTrace(String name, TracerDriver driver, long sessionId) {
this.name = name;
this.driver = driver;
this.sessionId = sessionId;
}
public String getName() {
return this.name;
}
public long getSessionId() {
return this.sessionId;
}
public void commit() {
if (this.driver instanceof AdvancedTracerDriver) {
((AdvancedTracerDriver) this.driver).addEvent(this);
} else {
this.driver.addCount(this.name, 1);
}
}
}
OperationTrace.java 0000664 0000000 0000000 00000010236 14420044236 0034334 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/drivers /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.drivers;
import org.apache.curator.drivers.TracerDriver;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.data.Stat;
import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;
/**
* Used to trace the metrics of a certain Zookeeper operation.
*/
public class OperationTrace
{
private final String name;
private final TracerDriver driver;
private int returnCode = KeeperException.Code.OK.intValue();
private long latencyMs;
private long requestBytesLength;
private long responseBytesLength;
private String path;
private boolean withWatcher;
private long sessionId;
private Stat stat;
private final long startTimeNanos = System.nanoTime();
public OperationTrace(String name, TracerDriver driver) {
this(name, driver, -1);
}
public OperationTrace(String name, TracerDriver driver, long sessionId) {
this.name = name;
this.driver = driver;
this.sessionId = sessionId;
}
public OperationTrace setReturnCode(int returnCode) {
this.returnCode = returnCode;
return this;
}
public OperationTrace setRequestBytesLength(long length) {
this.requestBytesLength = length;
return this;
}
public OperationTrace setRequestBytesLength(String data) {
if (data == null) {
return this;
}
try {
this.setRequestBytesLength(data.getBytes("UTF-8").length);
} catch (UnsupportedEncodingException e) {
// Ignore the exception.
}
return this;
}
public OperationTrace setRequestBytesLength(byte[] data) {
if (data == null) {
return this;
}
return this.setRequestBytesLength(data.length);
}
public OperationTrace setResponseBytesLength(long length) {
this.responseBytesLength = length;
return this;
}
public OperationTrace setResponseBytesLength(byte[] data) {
if (data == null) {
return this;
}
return this.setResponseBytesLength(data.length);
}
public OperationTrace setPath(String path) {
this.path = path;
return this;
}
public OperationTrace setWithWatcher(boolean withWatcher) {
this.withWatcher = withWatcher;
return this;
}
public OperationTrace setStat(Stat stat) {
this.stat = stat;
return this;
}
public String getName() {
return this.name;
}
public int getReturnCode() {
return this.returnCode;
}
public long getLatencyMs() {
return this.latencyMs;
}
public long getRequestBytesLength() {
return this.requestBytesLength;
}
public long getResponseBytesLength() {
return this.responseBytesLength;
}
public long getSessionId() {
return this.sessionId;
}
public String getPath() {
return this.path;
}
public boolean isWithWatcher() {
return this.withWatcher;
}
public Stat getStat() {
return this.stat;
}
public void commit() {
long elapsed = System.nanoTime() - startTimeNanos;
this.latencyMs = TimeUnit.MILLISECONDS.convert(elapsed, TimeUnit.NANOSECONDS);
if (this.driver instanceof AdvancedTracerDriver) {
((AdvancedTracerDriver) this.driver).addTrace(this);
} else {
this.driver.addTrace(this.name, elapsed, TimeUnit.NANOSECONDS);
}
}
}
TracerDriver.java 0000664 0000000 0000000 00000002571 14420044236 0034014 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/drivers /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.drivers;
import java.util.concurrent.TimeUnit;
/**
* Mechanism for timing methods and recording counters
*/
public interface TracerDriver
{
/**
* Record the given trace event
*
* @param name of the event
* @param time time event took
* @param unit time unit
*/
public void addTrace(String name, long time, TimeUnit unit);
/**
* Add to a named counter
*
* @param name name of the counter
* @param increment amount to increment
*/
public void addCount(String name, int increment);
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ensemble/ 0000775 0000000 0000000 00000000000 14420044236 0030743 5 ustar 00root root 0000000 0000000 EnsembleProvider.java 0000664 0000000 0000000 00000004303 14420044236 0034774 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ensemble /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.ensemble;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import java.io.Closeable;
import java.io.IOException;
/**
* Abstraction that provides the ZooKeeper connection string
*/
public interface EnsembleProvider extends Closeable
{
/**
* Curator will call this method when {@link CuratorZookeeperClient#start()} is
* called
*
* @throws Exception errors
*/
public void start() throws Exception;
/**
* Return the current connection string to use. Curator will call this each
* time it needs to create a ZooKeeper instance
*
* @return connection string (per {@link ZooKeeper#ZooKeeper(String, int, Watcher)} etc.)
*/
public String getConnectionString();
/**
* Curator will call this method when {@link CuratorZookeeperClient#close()} is called
*
* @throws IOException errors
*/
public void close() throws IOException;
/**
* A new connection string event was received
*
* @param connectionString the new connection string
*/
public void setConnectionString(String connectionString);
/**
* Return true if this ensemble provider supports {@link ZooKeeper#updateServerList(String)}
*
* @return true/false
*/
public boolean updateServerListEnabled();
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ensemble/fixed/ 0000775 0000000 0000000 00000000000 14420044236 0032042 5 ustar 00root root 0000000 0000000 FixedEnsembleProvider.java 0000664 0000000 0000000 00000005211 14420044236 0037052 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/ensemble/fixed /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.ensemble.fixed;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.curator.ensemble.EnsembleProvider;
import org.apache.zookeeper.ZooKeeper;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicReference;
/**
* Standard ensemble provider that wraps a fixed connection string
*/
public class FixedEnsembleProvider implements EnsembleProvider
{
private final AtomicReference connectionString = new AtomicReference<>();
private final boolean updateServerListEnabled;
/**
* The connection string to use
*
* @param connectionString connection string
*/
public FixedEnsembleProvider(String connectionString)
{
this(connectionString, true);
}
/**
* The connection string to use
*
* @param connectionString connection string
* @param updateServerListEnabled if true, allow Curator to call {@link ZooKeeper#updateServerList(String)}
*/
public FixedEnsembleProvider(String connectionString, boolean updateServerListEnabled)
{
this.updateServerListEnabled = updateServerListEnabled;
Preconditions.checkArgument(!Strings.isNullOrEmpty(connectionString), "connectionString cannot be null or empty");
this.connectionString.set(connectionString);
}
@Override
public void start() throws Exception
{
// NOP
}
@Override
public void close() throws IOException
{
// NOP
}
@Override
public void setConnectionString(String connectionString)
{
this.connectionString.set(connectionString);
}
@Override
public String getConnectionString()
{
return connectionString.get();
}
@Override
public boolean updateServerListEnabled()
{
return updateServerListEnabled;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry/ 0000775 0000000 0000000 00000000000 14420044236 0030316 5 ustar 00root root 0000000 0000000 BoundedExponentialBackoffRetry.java 0000664 0000000 0000000 00000003511 14420044236 0037173 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
import com.google.common.annotations.VisibleForTesting;
/**
* Retry policy that retries a set number of times with an increasing (up to a maximum bound) sleep time between retries
*/
public class BoundedExponentialBackoffRetry extends ExponentialBackoffRetry
{
private final int maxSleepTimeMs;
/**
* @param baseSleepTimeMs initial amount of time to wait between retries
* @param maxSleepTimeMs maximum amount of time to wait between retries
* @param maxRetries maximum number of times to retry
*/
public BoundedExponentialBackoffRetry(int baseSleepTimeMs, int maxSleepTimeMs, int maxRetries)
{
super(baseSleepTimeMs, maxRetries);
this.maxSleepTimeMs = maxSleepTimeMs;
}
@VisibleForTesting
public int getMaxSleepTimeMs()
{
return maxSleepTimeMs;
}
@Override
protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
{
return Math.min(maxSleepTimeMs, super.getSleepTimeMs(retryCount, elapsedTimeMs));
}
} ExponentialBackoffRetry.java 0000664 0000000 0000000 00000006060 14420044236 0035674 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
/**
* Retry policy that retries a set number of times with increasing sleep time between retries
*/
public class ExponentialBackoffRetry extends SleepingRetry
{
private static final Logger log = LoggerFactory.getLogger(ExponentialBackoffRetry.class);
private static final int MAX_RETRIES_LIMIT = 29;
private static final int DEFAULT_MAX_SLEEP_MS = Integer.MAX_VALUE;
private final Random random = new Random();
private final int baseSleepTimeMs;
private final int maxSleepMs;
/**
* @param baseSleepTimeMs initial amount of time to wait between retries
* @param maxRetries max number of times to retry
*/
public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries)
{
this(baseSleepTimeMs, maxRetries, DEFAULT_MAX_SLEEP_MS);
}
/**
* @param baseSleepTimeMs initial amount of time to wait between retries
* @param maxRetries max number of times to retry
* @param maxSleepMs max time in ms to sleep on each retry
*/
public ExponentialBackoffRetry(int baseSleepTimeMs, int maxRetries, int maxSleepMs)
{
super(validateMaxRetries(maxRetries));
this.baseSleepTimeMs = baseSleepTimeMs;
this.maxSleepMs = maxSleepMs;
}
@VisibleForTesting
public int getBaseSleepTimeMs()
{
return baseSleepTimeMs;
}
@Override
protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
{
// copied from Hadoop's RetryPolicies.java
long sleepMs = baseSleepTimeMs * Math.max(1, random.nextInt(1 << (retryCount + 1)));
if ( sleepMs > maxSleepMs )
{
log.warn(String.format("Sleep extension too large (%d). Pinning to %d", sleepMs, maxSleepMs));
sleepMs = maxSleepMs;
}
return sleepMs;
}
private static int validateMaxRetries(int maxRetries)
{
if ( maxRetries > MAX_RETRIES_LIMIT )
{
log.warn(String.format("maxRetries too large (%d). Pinning to %d", maxRetries, MAX_RETRIES_LIMIT));
maxRetries = MAX_RETRIES_LIMIT;
}
return maxRetries;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry/RetryForever.java0000664 0000000 0000000 00000003600 14420044236 0033616 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkArgument;
/**
* {@link RetryPolicy} implementation that always allowsRetry.
*/
public class RetryForever implements RetryPolicy
{
private static final Logger log = LoggerFactory.getLogger(RetryForever.class);
private final int retryIntervalMs;
public RetryForever(int retryIntervalMs)
{
checkArgument(retryIntervalMs > 0);
this.retryIntervalMs = retryIntervalMs;
}
@Override
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
{
try
{
sleeper.sleepFor(retryIntervalMs, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
log.warn("Error occurred while sleeping", e);
return false;
}
return true;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry/RetryNTimes.java 0000664 0000000 0000000 00000002402 14420044236 0033404 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
/**
* Retry policy that retries a max number of times
*/
public class RetryNTimes extends SleepingRetry
{
private final int sleepMsBetweenRetries;
public RetryNTimes(int n, int sleepMsBetweenRetries)
{
super(n);
this.sleepMsBetweenRetries = sleepMsBetweenRetries;
}
@Override
protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
{
return sleepMsBetweenRetries;
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry/RetryOneTime.java0000664 0000000 0000000 00000002023 14420044236 0033544 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
/**
* A retry policy that retries only once
*/
public class RetryOneTime extends RetryNTimes
{
public RetryOneTime(int sleepMsBetweenRetry)
{
super(1, sleepMsBetweenRetry);
}
}
RetryUntilElapsed.java 0000664 0000000 0000000 00000003240 14420044236 0034520 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
import org.apache.curator.RetrySleeper;
/**
* A retry policy that retries until a given amount of time elapses
*/
public class RetryUntilElapsed extends SleepingRetry
{
private final int maxElapsedTimeMs;
private final int sleepMsBetweenRetries;
public RetryUntilElapsed(int maxElapsedTimeMs, int sleepMsBetweenRetries)
{
super(Integer.MAX_VALUE);
this.maxElapsedTimeMs = maxElapsedTimeMs;
this.sleepMsBetweenRetries = sleepMsBetweenRetries;
}
@Override
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
{
return super.allowRetry(retryCount, elapsedTimeMs, sleeper) && (elapsedTimeMs < maxElapsedTimeMs);
}
@Override
protected long getSleepTimeMs(int retryCount, long elapsedTimeMs)
{
return sleepMsBetweenRetries;
}
}
SleepingRetry.java 0000664 0000000 0000000 00000003357 14420044236 0033706 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/retry /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.retry;
import org.apache.curator.RetryPolicy;
import org.apache.curator.RetrySleeper;
import java.util.concurrent.TimeUnit;
abstract class SleepingRetry implements RetryPolicy
{
private final int n;
protected SleepingRetry(int n)
{
this.n = n;
}
// made public for testing
public int getN()
{
return n;
}
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper)
{
if ( retryCount < n )
{
try
{
sleeper.sleepFor(getSleepTimeMs(retryCount, elapsedTimeMs), TimeUnit.MILLISECONDS);
}
catch ( InterruptedException e )
{
Thread.currentThread().interrupt();
return false;
}
return true;
}
return false;
}
protected abstract long getSleepTimeMs(int retryCount, long elapsedTimeMs);
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils/ 0000775 0000000 0000000 00000000000 14420044236 0030311 5 ustar 00root root 0000000 0000000 CloseableExecutorService.java 0000664 0000000 0000000 00000013532 14420044236 0036032 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Decoration on an ExecutorService that tracks created futures and provides
* a method to close futures created via this class
*/
public class CloseableExecutorService implements Closeable
{
private final Logger log = LoggerFactory.getLogger(CloseableExecutorService.class);
private final Set> futures = Sets.newSetFromMap(Maps., Boolean>newConcurrentMap());
private final ExecutorService executorService;
private final boolean shutdownOnClose;
protected final AtomicBoolean isOpen = new AtomicBoolean(true);
protected class InternalScheduledFutureTask implements Future
{
private final ScheduledFuture> scheduledFuture;
public InternalScheduledFutureTask(ScheduledFuture> scheduledFuture)
{
this.scheduledFuture = scheduledFuture;
futures.add(scheduledFuture);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning)
{
futures.remove(scheduledFuture);
return scheduledFuture.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled()
{
return scheduledFuture.isCancelled();
}
@Override
public boolean isDone()
{
return scheduledFuture.isDone();
}
@Override
public Void get() throws InterruptedException, ExecutionException
{
return null;
}
@Override
public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
{
return null;
}
}
protected class InternalFutureTask extends FutureTask
{
private final RunnableFuture task;
InternalFutureTask(RunnableFuture task)
{
super(task, null);
this.task = task;
futures.add(task);
}
protected void done()
{
futures.remove(task);
}
}
/**
* @param executorService the service to decorate
*/
public CloseableExecutorService(ExecutorService executorService)
{
this(executorService, false);
}
/**
* @param executorService the service to decorate
* @param shutdownOnClose if true, shutdown the executor service when this is closed
*/
public CloseableExecutorService(ExecutorService executorService, boolean shutdownOnClose)
{
this.executorService = Preconditions.checkNotNull(executorService, "executorService cannot be null");
this.shutdownOnClose = shutdownOnClose;
}
/**
* Returns true if this executor has been shut down.
*
* @return true if this executor has been shut down
*/
public boolean isShutdown()
{
return !isOpen.get();
}
@VisibleForTesting
int size()
{
return futures.size();
}
/**
* Closes any tasks currently in progress
*/
@Override
public void close()
{
isOpen.set(false);
Iterator> iterator = futures.iterator();
while ( iterator.hasNext() )
{
Future> future = iterator.next();
iterator.remove();
if ( !future.isDone() && !future.isCancelled() && !future.cancel(true) )
{
log.warn("Could not cancel " + future);
}
}
if (shutdownOnClose) {
executorService.shutdownNow();
}
}
/**
* Submits a value-returning task for execution and returns a Future
* representing the pending results of the task. Upon completion,
* this task may be taken or polled.
*
* @param task the task to submit
* @return a future to watch the task
*/
public Future submit(Callable task)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task));
executorService.execute(futureTask);
return futureTask;
}
/**
* Submits a Runnable task for execution and returns a Future
* representing that task. Upon completion, this task may be
* taken or polled.
*
* @param task the task to submit
* @return a future to watch the task
*/
public Future> submit(Runnable task)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task, null));
executorService.execute(futureTask);
return futureTask;
}
}
CloseableScheduledExecutorService.java 0000664 0000000 0000000 00000010330 14420044236 0037644 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import com.google.common.base.Preconditions;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
/**
* Decoration on an ScheduledExecutorService that tracks created futures and provides
* a method to close futures created via this class
*/
public class CloseableScheduledExecutorService extends CloseableExecutorService
{
private final ScheduledExecutorService scheduledExecutorService;
/**
* @param scheduledExecutorService the service to decorate
*/
public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService)
{
super(scheduledExecutorService, false);
this.scheduledExecutorService = scheduledExecutorService;
}
/**
* @param scheduledExecutorService the service to decorate
* @param shutdownOnClose if true, shutdown the executor service when this is closed
*/
public CloseableScheduledExecutorService(ScheduledExecutorService scheduledExecutorService, boolean shutdownOnClose)
{
super(scheduledExecutorService, shutdownOnClose);
this.scheduledExecutorService = scheduledExecutorService;
}
/**
* Creates and executes a one-shot action that becomes enabled
* after the given delay.
*
* @param task the task to execute
* @param delay the time from now to delay execution
* @param unit the time unit of the delay parameter
* @return a Future representing pending completion of
* the task and whose get() method will return
* null upon completion
*/
public Future> schedule(Runnable task, long delay, TimeUnit unit)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
InternalFutureTask futureTask = new InternalFutureTask(new FutureTask(task, null));
scheduledExecutorService.schedule(futureTask, delay, unit);
return futureTask;
}
/**
* Creates and executes a periodic action that becomes enabled first
* after the given initial delay, and subsequently with the
* given delay between the termination of one execution and the
* commencement of the next. If any execution of the task
* encounters an exception, subsequent executions are suppressed.
* Otherwise, the task will only terminate via cancellation or
* termination of the executor.
*
* @param task the task to execute
* @param initialDelay the time to delay first execution
* @param delay the delay between the termination of one
* execution and the commencement of the next
* @param unit the time unit of the initialDelay and delay parameters
* @return a Future representing pending completion of
* the task, and whose get() method will throw an
* exception upon cancellation
*/
public Future> scheduleWithFixedDelay(Runnable task, long initialDelay, long delay, TimeUnit unit)
{
Preconditions.checkState(isOpen.get(), "CloseableExecutorService is closed");
ScheduledFuture> scheduledFuture = scheduledExecutorService.scheduleWithFixedDelay(task, initialDelay, delay, unit);
return new InternalScheduledFutureTask(scheduledFuture);
}
}
CloseableUtils.java 0000664 0000000 0000000 00000004777 14420044236 0034026 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import com.google.common.io.Closeables;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Closeable;
import java.io.IOException;
/**
* This class adds back functionality that was removed in Guava v16.0.
*/
public class CloseableUtils
{
private static final Logger log = LoggerFactory.getLogger(CloseableUtils.class);
/**
*
* This method has been added because Guava has removed the
* {@code closeQuietly()} method from {@code Closeables} in v16.0. It's
* tempting simply to replace calls to {@code closeQuietly(closeable)}
* with calls to {@code close(closeable, true)} to close
* {@code Closeable}s while swallowing {@code IOException}s, but
* {@code close()} is declared as {@code throws IOException} whereas
* {@code closeQuietly()} is not, so it's not a drop-in replacement.
*
*
* On the whole, Guava is very backwards compatible. By fixing this nit,
* Curator can continue to support newer versions of Guava without having
* to bump its own dependency version.
*
*/
public static void closeQuietly(Closeable closeable)
{
try
{
// Here we've instructed Guava to swallow the IOException
Closeables.close(closeable, true);
}
catch ( IOException e )
{
// We instructed Guava to swallow the IOException, so this should
// never happen. Since it did, log it.
log.error("IOException should not have been thrown.", e);
}
}
}
Compatibility.java 0000664 0000000 0000000 00000007564 14420044236 0033722 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import org.apache.zookeeper.server.quorum.QuorumPeer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
/**
* Utils to help with ZK version compatibility
*/
public class Compatibility
{
private static final Logger log = LoggerFactory.getLogger(Compatibility.class);
private static final Method getReachableOrOneMethod;
private static final Field addrField;
private static final boolean hasPersistentWatchers;
static
{
Method localGetReachableOrOneMethod;
try
{
Class> multipleAddressesClass = Class.forName("org.apache.zookeeper.server.quorum.MultipleAddresses");
localGetReachableOrOneMethod = multipleAddressesClass.getMethod("getReachableOrOne");
log.info("Using org.apache.zookeeper.server.quorum.MultipleAddresses");
}
catch ( ReflectiveOperationException ignore )
{
localGetReachableOrOneMethod = null;
}
getReachableOrOneMethod = localGetReachableOrOneMethod;
Field localAddrField;
try
{
localAddrField = QuorumPeer.QuorumServer.class.getField("addr");
}
catch ( NoSuchFieldException e )
{
localAddrField = null;
log.error("Could not get addr field! Reconfiguration fail!");
}
addrField = localAddrField;
boolean localHasPersistentWatchers;
try
{
Class.forName("org.apache.zookeeper.AddWatchMode");
localHasPersistentWatchers = true;
}
catch ( ClassNotFoundException e )
{
localHasPersistentWatchers = false;
log.info("Persistent Watchers are not available in the version of the ZooKeeper library being used");
}
hasPersistentWatchers = localHasPersistentWatchers;
}
public static boolean hasGetReachableOrOneMethod()
{
return (getReachableOrOneMethod != null);
}
public static boolean hasAddrField()
{
return (addrField != null);
}
public static String getHostString(QuorumPeer.QuorumServer server)
{
InetSocketAddress address = null;
if ( getReachableOrOneMethod != null )
{
try
{
address = (InetSocketAddress)getReachableOrOneMethod.invoke(server.addr);
}
catch ( Exception e )
{
log.error("Could not call getReachableOrOneMethod.invoke({})", server.addr, e);
}
}
else if (addrField != null)
{
try
{
address = (InetSocketAddress)addrField.get(server);
}
catch ( Exception e )
{
log.error("Could not call addrField.get({})", server, e);
}
}
return address != null ? address.getHostString() : "unknown";
}
public static boolean hasPersistentWatchers()
{
return hasPersistentWatchers;
}
}
ConfigurableZookeeperFactory.java 0000664 0000000 0000000 00000002707 14420044236 0036717 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
import org.apache.zookeeper.client.ZKClientConfig;
/**
* Configurable ZookeeperFactory, by using org.apache.zookeeper.client.ZKClientConfig.
*
*/
public class ConfigurableZookeeperFactory extends DefaultZookeeperFactory
{
public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
boolean canBeReadOnly, ZKClientConfig zkClientConfig) throws Exception
{
return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly, zkClientConfig);
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils/DebugUtils.java 0000664 0000000 0000000 00000003075 14420044236 0033230 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
public class DebugUtils
{
public static final String PROPERTY_LOG_EVENTS = "curator-log-events";
public static final String PROPERTY_DONT_LOG_CONNECTION_ISSUES = "curator-dont-log-connection-problems";
public static final String PROPERTY_LOG_ONLY_FIRST_CONNECTION_ISSUE_AS_ERROR_LEVEL = "curator-log-only-first-connection-issue-as-error-level";
public static final String PROPERTY_REMOVE_WATCHERS_IN_FOREGROUND = "curator-remove-watchers-in-foreground";
public static final String PROPERTY_VALIDATE_NAMESPACE_WATCHER_MAP_EMPTY = "curator-validate-namespace-watcher-map-empty";
public static final String PROPERTY_VALIDATE_NO_REMAINING_WATCHERS = "curator-validate-no-remaining-watchers";
private DebugUtils()
{
}
}
DefaultTracerDriver.java 0000664 0000000 0000000 00000003073 14420044236 0035001 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import org.apache.curator.drivers.TracerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
/**
* Default tracer driver
*/
public class DefaultTracerDriver implements TracerDriver
{
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
public void addTrace(String name, long time, TimeUnit unit)
{
if ( log.isTraceEnabled() )
{
log.trace("Trace: " + name + " - " + TimeUnit.MILLISECONDS.convert(time, unit) + " ms");
}
}
@Override
public void addCount(String name, int increment)
{
if ( log.isTraceEnabled() )
{
log.trace("Counter " + name + ": " + increment);
}
}
}
DefaultZookeeperFactory.java 0000664 0000000 0000000 00000002411 14420044236 0035673 0 ustar 00root root 0000000 0000000 curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.admin.ZooKeeperAdmin;
public class DefaultZookeeperFactory implements ZookeeperFactory
{
@Override
public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception
{
return new ZooKeeperAdmin(connectString, sessionTimeout, watcher, canBeReadOnly);
}
}
curator-apache-curator-5.5.0/curator-client/src/main/java/org/apache/curator/utils/EnsurePath.java 0000664 0000000 0000000 00000012363 14420044236 0033237 0 ustar 00root root 0000000 0000000 /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.curator.utils;
import org.apache.curator.CuratorZookeeperClient;
import org.apache.curator.RetryLoop;
import org.apache.zookeeper.ZooKeeper;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicReference;
/**
*
* Utility to ensure that a particular path is created.
*
*
* The first time it is used, a synchronized call to {@link ZKPaths#mkdirs(ZooKeeper, String)} is made to
* ensure that the entire path has been created (with an empty byte array if needed). Subsequent
* calls with the instance are un-synchronized NOPs.
*
*
* Usage:
*
*
* EnsurePath ensurePath = new EnsurePath(aFullPathToEnsure);
* ...
* String nodePath = aFullPathToEnsure + "/foo";
* ensurePath.ensure(zk); // first time syncs and creates if needed
* zk.create(nodePath, ...);
* ...
* ensurePath.ensure(zk); // subsequent times are NOPs
* zk.create(nodePath, ...);
*
*
* @deprecated Since 2.9.0 - Prefer CuratorFramework.create().creatingParentContainersIfNeeded() or CuratorFramework.exists().creatingParentContainersIfNeeded()
*/
@Deprecated
public class EnsurePath
{
private final String path;
private final boolean makeLastNode;
private final InternalACLProvider aclProvider;
private final AtomicReference helper;
private static final Helper doNothingHelper = new Helper()
{
@Override
public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception
{
// NOP
}
};
interface Helper
{
public void ensure(CuratorZookeeperClient client, String path, final boolean makeLastNode) throws Exception;
}
/**
* @param path the full path to ensure
*/
public EnsurePath(String path)
{
this(path, null, true, null);
}
/**
* @param path the full path to ensure
* @param aclProvider if not null, the ACL provider to use when creating parent nodes
*/
public EnsurePath(String path, InternalACLProvider aclProvider)
{
this(path, null, true, aclProvider);
}
/**
* First time, synchronizes and makes sure all nodes in the path are created. Subsequent calls
* with this instance are NOPs.
*
* @param client ZK client
* @throws Exception ZK errors
*/
public void ensure(CuratorZookeeperClient client) throws Exception
{
Helper localHelper = helper.get();
localHelper.ensure(client, path, makeLastNode);
}
/**
* Returns a view of this EnsurePath instance that does not make the last node.
* i.e. if the path is "/a/b/c" only "/a/b" will be ensured
*
* @return view
*/
public EnsurePath excludingLast()
{
return new EnsurePath(path, helper, false, aclProvider);
}
protected EnsurePath(String path, AtomicReference helper, boolean makeLastNode, InternalACLProvider aclProvider)
{
this.path = path;
this.makeLastNode = makeLastNode;
this.aclProvider = aclProvider;
this.helper = (helper != null) ? helper : new AtomicReference(new InitialHelper());
}
/**
* Returns the path being Ensured
*
* @return the path being ensured
*/
public String getPath()
{
return this.path;
}
protected boolean asContainers()
{
return false;
}
private class InitialHelper implements Helper
{
private boolean isSet = false; // guarded by synchronization
@Override
public synchronized void ensure(final CuratorZookeeperClient client, final String path, final boolean makeLastNode) throws Exception
{
if ( !isSet )
{
RetryLoop.callWithRetry
(
client,
new Callable