diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..580cd305b56be53270602277b76a21ea664e84b4 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/Dockerfile @@ -0,0 +1,26 @@ +# Copyright 2023 Google LLC +# +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +# Copy/Run this now to make the cache more resilient. +COPY fuzzbench_install_dependencies /usr/local/bin +RUN fuzzbench_install_dependencies + +ENV OSS_FUZZ_ON_DEMAND=1 + +COPY fuzzbench_build fuzzbench_run_fuzzer fuzzbench_measure /usr/local/bin/ diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure new file mode 100644 index 0000000000000000000000000000000000000000..ba9a413a0b59557a4e8d029aa413967bd700041c --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_measure @@ -0,0 +1,32 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# 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. +# +################################################################################ + +# TODO(metzman): Make these configurable. +export DB_PATH=$OUT/experiment.db +export SNAPSHOT_PERIOD=30 +export EXPERIMENT_FILESTORE=$OUT/filestore +export MAX_TOTAL_TIME=120 +export EXPERIMENT=oss-fuzz-on-demand + +rm -f $DB_PATH + +# FUZZER=mopt BENCHMARK=skcms + +export SQL_DATABASE_URL=sqlite:///$DB_PATH + +cd $FUZZBENCH_PATH +PYTHONPATH=. python3 -B experiment/measurer/standalone.py $MAX_TOTAL_TIME diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer new file mode 100644 index 0000000000000000000000000000000000000000..008fdbb05cc390c3af022c6d2204a3014abcc8b9 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-fuzzbench/fuzzbench_run_fuzzer @@ -0,0 +1,41 @@ +#! /bin/bash -eux +# Copyright 2023 Google LLC +# +# 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. +# +################################################################################ + +export RUNNER_NICENESS="-5" +export EXPERIMENT_FILESTORE=$OUT/filestore +export EXPERIMENT=oss-fuzz-on-demand +export OSS_FUZZ_ON_DEMAND=1 +export OUTPUT_CORPUS_DIR=/output-corpus +export SEED_CORPUS_DIR=/input-corpus +mkdir $SEED_CORPUS_DIR +rm -rf $OUTPUT_CORPUS_DIR +mkdir $OUTPUT_CORPUS_DIR +export FUZZER=$FUZZING_ENGINE +# TODO(metzman): Make this configurable. +export MAX_TOTAL_TIME=120 +export SNAPSHOT_PERIOD=30 +export TRIAL_ID=1 +export FORCE_LOCAL=1 + +# BENCHMARK, FUZZ_TARGET +cd $OUT + +# Prevent permissions issues with pyc files and docker. +cp -r $FUZZBENCH_PATH /tmp/fuzzbench + +PYTHONPATH=/tmp/fuzzbench nice -n $RUNNER_NICENESS python3 -B -u /tmp/fuzzbench/experiment/runner.py +cat $EXPERIMENT_FILESTORE/$EXPERIMENT/experiment-folders/$BENCHMARK-$FUZZER/trial-$TRIAL_ID/results/fuzzer-log.txt diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c new file mode 100644 index 0000000000000000000000000000000000000000..d613ce64b78fcbce7180f48587ac5f8085ae402f --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-go/gosigfuzz.c @@ -0,0 +1,47 @@ +/* + * Copyright 2023 Google LLC + + * 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. +*/ + +#include +#include + +static void fixSignalHandler(int signum) { + struct sigaction new_action; + struct sigaction old_action; + sigemptyset (&new_action.sa_mask); + sigaction (signum, NULL, &old_action); + new_action.sa_flags = old_action.sa_flags | SA_ONSTACK; + new_action.sa_sigaction = old_action.sa_sigaction; + new_action.sa_handler = old_action.sa_handler; + sigaction (signum, &new_action, NULL); +} + +static void FixStackSignalHandler() { + fixSignalHandler(SIGSEGV); + fixSignalHandler(SIGABRT); + fixSignalHandler(SIGALRM); + fixSignalHandler(SIGINT); + fixSignalHandler(SIGTERM); + fixSignalHandler(SIGBUS); + fixSignalHandler(SIGFPE); + fixSignalHandler(SIGXFSZ); + fixSignalHandler(SIGUSR1); + fixSignalHandler(SIGUSR2); +} + +int LLVMFuzzerInitialize(int *argc, char ***argv) { + FixStackSignalHandler(); + return 0; +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e558984c194daff35064cba3c5118c76f3e5c582 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/Dockerfile @@ -0,0 +1,22 @@ +# Copyright 2021 Google LLC +# +# 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. +# +################################################################################ + +ARG IMG_TAG=latest +FROM ghcr.io/aixcc-finals/base-builder:${IMG_TAG} + +RUN install_swift.sh + +COPY precompile_swift /usr/local/bin/ diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift new file mode 100644 index 0000000000000000000000000000000000000000..ab855a620191656e572d6a68a869e26f020b0dc5 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder-swift/precompile_swift @@ -0,0 +1,33 @@ +#!/bin/bash -eu +# Copyright 2021 Google LLC +# +# 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. +# +################################################################################ + +cp /usr/local/bin/llvm-symbolizer-swift $OUT/llvm-symbolizer + +export SWIFTFLAGS="-Xswiftc -parse-as-library -Xswiftc -static-stdlib --static-swift-stdlib" +if [ "$SANITIZER" = "coverage" ] +then + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -profile-generate -Xswiftc -profile-coverage-mapping -Xswiftc -sanitize=fuzzer" +else + export SWIFTFLAGS="$SWIFTFLAGS -Xswiftc -sanitize=fuzzer,$SANITIZER --sanitize=$SANITIZER" + for f in $CFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcc=$f" + done + + for f in $CXXFLAGS; do + export SWIFTFLAGS="$SWIFTFLAGS -Xcxx=$f" + done +fi diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..42dcf3e0ba244c6d59a6ab3d38af5adcd5f92fbe --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/.gitignore @@ -0,0 +1,4 @@ +dist +pysecsan.egg-info* +build +.venv diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py new file mode 100644 index 0000000000000000000000000000000000000000..388cb331c20f05d6f876ca3589e6490705e4fc5c --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/pysecsan/redos.py @@ -0,0 +1,84 @@ +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Sanitizer for regular expression dos.""" + +# pylint: disable=protected-access + +import time +import os +from pysecsan import sanlib + +START_RE_TIME = None + + +# Hooks for regular expressions. +# Main problem is to identify ReDOS attemps. This is a non-trivial task +# - https://arxiv.org/pdf/1701.04045.pdf +# - https://dl.acm.org/doi/pdf/10.1145/3236024.3236027 +# and the current approach we use is simply check for extensive computing time. +# In essence, this is more of a refinement of traditional timeout checker from +# the fuzzer, which, effectively will detect these types of attacks by way of +# timeouts. +# +# Perhaps the smartest would be to use something like e.g. +# https://github.com/doyensec/regexploit to scan the regex patterns. +# Other heuristics without going too technical on identifying super-linear +# regexes: +# - check +# - if 'taint' exists in re.compile(xx) +# - check +# - for backtracking possbility in PATTERN within re.comile(PATTERN) +# - and +# - 'taint' in findall(XX) calls. +# pylint: disable=global-statement +def hook_post_exec_re_pattern_findall(self, re_str): + """Hook post exeution re.compile().findall().""" + _ = self # Satisfy lint + global START_RE_TIME + try: + endtime = time.time() - START_RE_TIME + if endtime > 4: + sanlib.abort_with_issue(f'Potential ReDOS attack.\n {re_str}', 'ReDOS') + except NameError: + sanlib.sanitizer_log( + 'starttime is not set, which it should have. Error in PySecSan', + sanlib.LOG_INFO) + os._exit(1) + + +def hook_pre_exec_re_pattern_findall(self, string): + """Hook pre execution of re.pattern().findall().""" + _ = (self, string) # Satisfy lint + global START_RE_TIME + START_RE_TIME = time.time() + + +def hook_post_exec_re_compile(retval, pattern, flags=None): + """Hook for re.compile post execution to hook returned objects functions.""" + _ = (pattern, flags) # Satisfy lint + sanlib.sanitizer_log('Inside of post compile hook', sanlib.LOG_DEBUG) + wrapper_object = sanlib.create_object_wrapper( + findall=(hook_pre_exec_re_pattern_findall, + hook_post_exec_re_pattern_findall)) + hooked_object = wrapper_object(retval) + return hooked_object + + +def hook_pre_exec_re_compile(pattern, flags=None): + """Check if tainted input exists in pattern. If so, likely chance of making + ReDOS possible.""" + _ = (pattern, flags) # Satisfy lint + sanlib.sanitizer_log('Inside re compile hook', sanlib.LOG_DEBUG) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d0e2e6fc6cca7aa38885792bede7e10874b3e13b --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/README.md @@ -0,0 +1 @@ +# Tests including Proof of Exploits diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..c980f30c44e1be351bb7c82ed00c7f089a6fe469 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/eval_command_injection.py @@ -0,0 +1,52 @@ +#!/usr/bin/python3 +# Copyright 2022 Google LLC +# +# 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. +"""Fuzzer targetting command injection of eval.""" +# pylint: disable=eval-used + +import sys +import atheris +import pysecsan + +pysecsan.add_hooks() + + +def list_files_perhaps(param, magicval): + """Pass fuzzer data into eval.""" + if len(param) < 3: + return + if magicval == 1337: + try: + eval("FROMFUZZ") + except ValueError: + pass + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + list_files_perhaps(fdp.ConsumeUnicodeNoSurrogates(24), + fdp.ConsumeIntInRange(500, 1500)) + + +def main(): + """Set up and start fuzzing.""" + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/build.sh b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..e95473cfdb58d84b8ff36f6b3140e8f4995d40f3 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/build.sh @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ + +python3 -m pip install pysecsan + +git clone https://github.com/ansible/ansible-runner/ +cd ansible-runner +git checkout cdc0961df51fa1e10b44371944aafe5ae140b98c +python3 -m pip install . +cd .. +python3 fuzz_ansible_runner.py diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/fuzz_ansible_runner.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/fuzz_ansible_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..44bd5ecea4e0f12fe4c955c0f88f2f118d40c9b3 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/ansible-runner-cve-2021-4041/fuzz_ansible_runner.py @@ -0,0 +1,64 @@ +#!/usr/bin/python3 +# Copyright 2022 Google LLC +# +# 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. +"""Targets: https://github.com/advisories/GHSA-6j58-grhv-2769.""" + +import sys +import atheris +import pexpect +import pysecsan +import ansible_runner +from ansible_runner.config.runner import RunnerConfig + +pysecsan.add_hooks() + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + + conf = RunnerConfig('/tmp/') + conf.suppress_ansible_output = True + conf.expect_passwords = {pexpect.TIMEOUT: None, pexpect.EOF: None} + conf.cwd = str('/tmp/') + conf.env = {} + conf.job_timeout = 10 + conf.idle_timeout = 0 + conf.pexpect_timeout = 2. + conf.pexpect_use_poll = True + conf.command = 'from_fuzzer' + + runner = ansible_runner.Runner(conf) + runner.resource_profiling = True + # rc.resource_profiling_base_cgroup = "; exec-san" + assistance = True + if assistance and fdp.ConsumeIntInRange(1, 100) > 80: + conf.resource_profiling_base_cgroup = 'FROMFUZZ' + else: + conf.resource_profiling_base_cgroup = fdp.ConsumeUnicodeNoSurrogates(24) + try: + runner.run() + except (RuntimeError, ValueError, TypeError) as _: + pass + + +def main(): + """Set up and start fuzzing.""" + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/build.sh b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f193a4c2a441d9e179dac4685fa0938ae2ad402 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/build.sh @@ -0,0 +1,21 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ + +python3 -m pip install pysecsan + +python3 -m pip install libvcs==0.11.0 +python3 ./fuzz_libvcs.py diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/fuzz_libvcs.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/fuzz_libvcs.py new file mode 100644 index 0000000000000000000000000000000000000000..c2bdb5890f8057da8e0754a71b96826b4077cd15 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/libvcs-cve-2022-21187/fuzz_libvcs.py @@ -0,0 +1,45 @@ +#!/usr/bin/python3 +# Copyright 2022 Google LLC +# +# 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. +"""Targets https://github.com/advisories/GHSA-mv2w-4jqc-6fg4.""" + +import sys +import atheris +import pysecsan +from libvcs.shortcuts import create_repo + +pysecsan.add_hooks() + + +def test_one_input(data): + """Target code injection in libvcs.""" + fdp = atheris.FuzzedDataProvider(data) + mercurial_repo = create_repo(url=fdp.ConsumeUnicodeNoSurrogates(128), + vcs='hg', + repo_dir='./') + try: + mercurial_repo.update_repo() + except (ValueError, FileNotFoundError) as exception: + _ = exception # Satisfy lint + + +def main(): + """Set up and start fuzzing.""" + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/build.sh b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..9311619c3fea1513973f0a559b69f0c61b134c8f --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/build.sh @@ -0,0 +1,25 @@ +#!/bin/bash -eu +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ + +python3 -m pip install pysecsan + +git clone https://github.com/python-ldap/python-ldap +cd python-ldap +git checkout 404c36b702c5b3a7e60729745c8bda16098b1472 +python3 -m pip install . +cd ../ +python3 ./fuzz_ldap.py diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py new file mode 100644 index 0000000000000000000000000000000000000000..bacc9b209537c7cf5995f94134a635cca326d11f --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/python-ldap-GHSL-2021-117/fuzz_ldap.py @@ -0,0 +1,42 @@ +#!/usr/bin/python3 +# Copyright 2022 Google LLC +# +# 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. +"""Targets: https://github.com/python-ldap/python-ldap/security/advisories/GHSA-r8wq-qrxc-hmcm""" # pylint: disable=line-too-long + +import sys +import atheris +import pysecsan +import ldap.schema + +pysecsan.add_hooks() + + +def test_one_input(data): + """Fuzzer targetting regex dos in ldap.""" + fdp = atheris.FuzzedDataProvider(data) + try: + ldap.schema.split_tokens(fdp.ConsumeUnicodeNoSurrogates(1024)) + except ValueError: + pass + + +def main(): + """Set up and start fuzzing.""" + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py new file mode 100644 index 0000000000000000000000000000000000000000..a40fe6d711777951a05cfab7c1a76d8e238b8d02 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/poe/pytorch-lightning-1.5.10/fuzz_pytorch_lightning.py @@ -0,0 +1,67 @@ +#!/usr/local/bin/python3 +# +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Exploit pytorch lightning with fuzzer's input as a random env variable. +This PoC is extended from a report in GitHub Advisory Database: +https://github.com/advisories/GHSA-r5qj-cvf9-p85h +The original report documents an exploit using a specific environment variable, +we show a way to achieve the same exploit with an arbitrary env variable. +""" + +import os +import sys +import atheris +import pysecsan + +pysecsan.add_hooks() + +with atheris.instrument_imports(): + from pytorch_lightning import Trainer + from pytorch_lightning.utilities.argparse import parse_env_variables + + +def prepare_fuzzing_input(data): + """Prepare the data needed by the exploit with input data from fuzzers.""" + data = data.replace(b'\0', b'') + env_name = 'AN_ARBITRARY_ENV_NAME' + return data, env_name + + +def exploit_target(env_value, env_name): + """This target is based on a snippet from the official documentation of + `parse_env_variables`: + https://pytorch-lightning.readthedocs.io/en/stable/api/pytorch_lightning.utilities.argparse.html # pylint: disable=line-too-long + It might not be the most realistic example, + but serves as a PoC to show that SystemSan works for Python.""" + os.environb[env_name.encode()] = env_value + parse_env_variables(Trainer, template=env_name) + + +def TestOneInput(data): # pylint: disable=invalid-name + """Exploit the target only with input data from fuzzers.""" + env_value, env_name = prepare_fuzzing_input(data) + exploit_target(env_value, env_name) + + +def main(): + """Fuzz target with atheris.""" + atheris.Setup(sys.argv, TestOneInput) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py new file mode 100644 index 0000000000000000000000000000000000000000..da05135f91e6ba33e1f4e868adb1ef778223d760 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-builder/sanitizers/pysecsan/tests/subprocess_popen_injection.py @@ -0,0 +1,51 @@ +#!/usr/bin/python3 +# Copyright 2022 Google LLC +# +# 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. +"""Fuzzer displaying insecure use of subprocess.Popen.""" + +import sys +import subprocess +import atheris +import pysecsan + + +def list_files_perhaps(param): + """Insecure call to Popen.""" + try: + subprocess.Popen(' '.join(['ls', '-la', param]), shell=True) + except ValueError: + pass + + +def test_one_input(data): + """Fuzzer entrypoint.""" + fdp = atheris.FuzzedDataProvider(data) + + if fdp.ConsumeIntInRange(1, 10) == 5: + list_files_perhaps('FROMFUZZ') + else: + list_files_perhaps('.') + + +def main(): + """Set up and start fuzzing.""" + pysecsan.add_hooks() + + atheris.instrument_all() + atheris.Setup(sys.argv, test_one_input, enable_python_coverage=True) + atheris.Fuzz() + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.mod b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..c82e4565f29aa96933c22df8ffdd37af57f98eed --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.mod @@ -0,0 +1,10 @@ +module oss-fuzz.com/gocoverage/convertcorpus + +go 1.19 + +require github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20221110144148-3ffc89b74f84 + +require ( + github.com/AdaLogics/go-fuzz-headers v0.0.0-20220824214621-3c06a36a6952 // indirect + github.com/cyphar/filepath-securejoin v0.2.3 // indirect +) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.sum b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..7b7d20e202530161b2ca1cee6f36a56e8cc4b422 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/go.sum @@ -0,0 +1,24 @@ +github.com/AdaLogics/go-fuzz-headers v0.0.0-20220824214621-3c06a36a6952 h1:cs1LC1MGKD1O4neR89Rc24t0u15Vs5ASfUQ2tLr/KbY= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20220824214621-3c06a36a6952/go.mod h1:i9fr2JpcEcY/IHEvzCM3qXUZYOQHgR89dt4es1CgMhc= +github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20221110144148-3ffc89b74f84 h1:a0NR83n+t4XyUh32ifxu6XsmeLMKyOx5Lxub9IeBM7k= +github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20221110144148-3ffc89b74f84/go.mod h1:pXIs8t4wo19ehhsffZsAZxSQ+oPUF41iiDrUaIDWKFU= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cyphar/filepath-securejoin v0.2.3 h1:YX6ebbZCZP7VkM3scTTokDgBL2TY741X51MTk3ycuNI= +github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/main.go b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/main.go new file mode 100644 index 0000000000000000000000000000000000000000..43e2c7ea7dd0042307f86213ecb46c4928cb6c51 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/convertcorpus/main.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "log" + "os" + "path/filepath" + + "github.com/AdamKorcz/go-118-fuzz-build/coverage" +) + +// reads all corpus files in a directory and converts +// them from libFuzzer format to native Go format. +func main() { + if len(os.Args) != 3 { + fmt.Println(os.Args) + log.Fatalf("need exactly two argument") + } + FUZZERNAME := os.Args[1] + CORPUS_PATH := os.Args[2] + + filepath.Walk(CORPUS_PATH, func(path string, info os.FileInfo, err error) error { + if err != nil { + return nil + } + if !info.Mode().IsRegular() { + return nil + } + libFuzzerSeed, err := os.ReadFile(path) + if err != nil { + panic(err) + } + out := os.Getenv("OUT") + fuzzerContents, err := os.ReadFile(filepath.Join(out, "rawfuzzers", FUZZERNAME)) + if err != nil { + panic(err) + } + goSeed := coverage.ConvertLibfuzzerSeedToGoSeed(fuzzerContents, libFuzzerSeed, FUZZERNAME) + err = os.Remove(path) + if err != nil { + panic(err) + } + f, err := os.Create(path) + if err != nil { + panic(err) + } + defer f.Close() + _, err = f.Write([]byte(goSeed)) + if err != nil { + panic(err) + } + return nil + }) +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.mod b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..b0b57216ea3083a5451fb862138bebba90b81f80 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/go.mod @@ -0,0 +1,8 @@ +module oss-fuzz.com/gocoverage + +go 1.14 + +require ( + github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5 + golang.org/x/tools v0.1.0 +) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..455fb10875ed00a441170736f454c383a80ad7b1 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2015, Wade Simmons +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/gocovmerge.go b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/gocovmerge.go new file mode 100644 index 0000000000000000000000000000000000000000..e8099839e13aa6ba5504bf77af9969fc48b30d29 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovmerge/gocovmerge.go @@ -0,0 +1,111 @@ +// gocovmerge takes the results from multiple `go test -coverprofile` runs and +// merges them into one profile +package main + +import ( + "flag" + "fmt" + "io" + "log" + "os" + "sort" + + "golang.org/x/tools/cover" +) + +func mergeProfiles(p *cover.Profile, merge *cover.Profile) { + if p.Mode != merge.Mode { + log.Fatalf("cannot merge profiles with different modes") + } + // Since the blocks are sorted, we can keep track of where the last block + // was inserted and only look at the blocks after that as targets for merge + startIndex := 0 + for _, b := range merge.Blocks { + startIndex = mergeProfileBlock(p, b, startIndex) + } +} + +func mergeProfileBlock(p *cover.Profile, pb cover.ProfileBlock, startIndex int) int { + sortFunc := func(i int) bool { + pi := p.Blocks[i+startIndex] + return pi.StartLine >= pb.StartLine && (pi.StartLine != pb.StartLine || pi.StartCol >= pb.StartCol) + } + + i := 0 + if sortFunc(i) != true { + i = sort.Search(len(p.Blocks)-startIndex, sortFunc) + } + i += startIndex + if i < len(p.Blocks) && p.Blocks[i].StartLine == pb.StartLine && p.Blocks[i].StartCol == pb.StartCol { + if p.Blocks[i].EndLine != pb.EndLine || p.Blocks[i].EndCol != pb.EndCol { + log.Fatalf("OVERLAP MERGE: %v %v %v", p.FileName, p.Blocks[i], pb) + } + switch p.Mode { + case "set": + p.Blocks[i].Count |= pb.Count + case "count", "atomic": + p.Blocks[i].Count += pb.Count + default: + log.Fatalf("unsupported covermode: '%s'", p.Mode) + } + } else { + if i > 0 { + pa := p.Blocks[i-1] + if pa.EndLine >= pb.EndLine && (pa.EndLine != pb.EndLine || pa.EndCol > pb.EndCol) { + log.Fatalf("OVERLAP BEFORE: %v %v %v", p.FileName, pa, pb) + } + } + if i < len(p.Blocks)-1 { + pa := p.Blocks[i+1] + if pa.StartLine <= pb.StartLine && (pa.StartLine != pb.StartLine || pa.StartCol < pb.StartCol) { + log.Fatalf("OVERLAP AFTER: %v %v %v", p.FileName, pa, pb) + } + } + p.Blocks = append(p.Blocks, cover.ProfileBlock{}) + copy(p.Blocks[i+1:], p.Blocks[i:]) + p.Blocks[i] = pb + } + return i + 1 +} + +func addProfile(profiles []*cover.Profile, p *cover.Profile) []*cover.Profile { + i := sort.Search(len(profiles), func(i int) bool { return profiles[i].FileName >= p.FileName }) + if i < len(profiles) && profiles[i].FileName == p.FileName { + mergeProfiles(profiles[i], p) + } else { + profiles = append(profiles, nil) + copy(profiles[i+1:], profiles[i:]) + profiles[i] = p + } + return profiles +} + +func dumpProfiles(profiles []*cover.Profile, out io.Writer) { + if len(profiles) == 0 { + return + } + fmt.Fprintf(out, "mode: %s\n", profiles[0].Mode) + for _, p := range profiles { + for _, b := range p.Blocks { + fmt.Fprintf(out, "%s:%d.%d,%d.%d %d %d\n", p.FileName, b.StartLine, b.StartCol, b.EndLine, b.EndCol, b.NumStmt, b.Count) + } + } +} + +func main() { + flag.Parse() + + var merged []*cover.Profile + + for _, file := range flag.Args() { + profiles, err := cover.ParseProfiles(file) + if err != nil { + log.Fatalf("failed to parse profiles: %v", err) + } + for _, p := range profiles { + merged = addProfile(merged, p) + } + } + + dumpProfiles(merged, os.Stdout) +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovsum/gocovsum.go b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovsum/gocovsum.go new file mode 100644 index 0000000000000000000000000000000000000000..660c4d13a364e073e4cad39d542fe56cd611b3e9 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/gocovsum/gocovsum.go @@ -0,0 +1,171 @@ +// Copyright 2023 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + + "go/ast" + "go/parser" + "go/token" + + "golang.org/x/tools/cover" +) + +type CoverageTotal struct { + Count int `json:"count"` + Covered int `json:"covered"` + Uncovered int `json:"notcovered"` + Percent float64 `json:"percent"` +} + +type CoverageTotals struct { + Functions CoverageTotal `json:"functions,omitempty"` + Lines CoverageTotal `json:"lines,omitempty"` + Regions CoverageTotal `json:"regions,omitempty"` + Instantiations CoverageTotal `json:"instantiations,omitempty"` + Branches CoverageTotal `json:"branches,omitempty"` +} + +type CoverageFile struct { + Summary CoverageTotals `json:"summary,omitempty"` + Filename string `json:"filename,omitempty"` +} + +type CoverageData struct { + Totals CoverageTotals `json:"totals,omitempty"` + Files []CoverageFile `json:"files,omitempty"` +} + +type PositionInterval struct { + start token.Position + end token.Position +} + +type CoverageSummary struct { + Data []CoverageData `json:"data,omitempty"` + Type string `json:"type,omitempty"` + Version string `json:"version,omitempty"` +} + +func isFunctionCovered(s token.Position, e token.Position, blocks []cover.ProfileBlock) bool { + for _, b := range blocks { + if b.StartLine >= s.Line && b.StartLine <= e.Line && b.EndLine >= s.Line && b.EndLine <= e.Line { + if b.Count > 0 { + return true + } + } + } + return false +} + +func computePercent(s *CoverageTotals) { + if s.Regions.Count > 0 { + s.Regions.Percent = float64(100*s.Regions.Covered) / float64(s.Regions.Count) + } + if s.Lines.Count > 0 { + s.Lines.Percent = float64(100*s.Lines.Covered) / float64(s.Lines.Count) + } + if s.Functions.Count > 0 { + s.Functions.Percent = float64(100*s.Functions.Covered) / float64(s.Functions.Count) + } +} + +func main() { + flag.Parse() + + if len(flag.Args()) != 1 { + log.Fatalf("needs exactly one argument") + } + profiles, err := cover.ParseProfiles(flag.Args()[0]) + if err != nil { + log.Fatalf("failed to parse profiles: %v", err) + } + r := CoverageSummary{} + r.Type = "oss-fuzz.go.coverage.json.export" + r.Version = "2.0.1" + r.Data = make([]CoverageData, 1) + for _, p := range profiles { + fset := token.NewFileSet() // positions are relative to fset + f, err := parser.ParseFile(fset, p.FileName, nil, 0) + if err != nil { + log.Printf("failed to parse go file: %v", err) + continue + } + fileCov := CoverageFile{} + fileCov.Filename = p.FileName + ast.Inspect(f, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.FuncLit: + startf := fset.Position(x.Pos()) + endf := fset.Position(x.End()) + fileCov.Summary.Functions.Count++ + if isFunctionCovered(startf, endf, p.Blocks) { + fileCov.Summary.Functions.Covered++ + } else { + fileCov.Summary.Functions.Uncovered++ + } + case *ast.FuncDecl: + startf := fset.Position(x.Pos()) + endf := fset.Position(x.End()) + fileCov.Summary.Functions.Count++ + if isFunctionCovered(startf, endf, p.Blocks) { + fileCov.Summary.Functions.Covered++ + } else { + fileCov.Summary.Functions.Uncovered++ + } + } + return true + }) + + for _, b := range p.Blocks { + fileCov.Summary.Regions.Count++ + if b.Count > 0 { + fileCov.Summary.Regions.Covered++ + } else { + fileCov.Summary.Regions.Uncovered++ + } + + fileCov.Summary.Lines.Count += b.NumStmt + if b.Count > 0 { + fileCov.Summary.Lines.Covered += b.NumStmt + } else { + fileCov.Summary.Lines.Uncovered += b.NumStmt + } + } + r.Data[0].Totals.Regions.Count += fileCov.Summary.Regions.Count + r.Data[0].Totals.Regions.Covered += fileCov.Summary.Regions.Covered + r.Data[0].Totals.Regions.Uncovered += fileCov.Summary.Regions.Uncovered + r.Data[0].Totals.Lines.Count += fileCov.Summary.Lines.Count + r.Data[0].Totals.Lines.Covered += fileCov.Summary.Lines.Covered + r.Data[0].Totals.Lines.Uncovered += fileCov.Summary.Lines.Uncovered + r.Data[0].Totals.Functions.Count += fileCov.Summary.Functions.Count + r.Data[0].Totals.Functions.Covered += fileCov.Summary.Functions.Covered + r.Data[0].Totals.Functions.Uncovered += fileCov.Summary.Functions.Uncovered + + computePercent(&fileCov.Summary) + r.Data[0].Files = append(r.Data[0].Files, fileCov) + } + + computePercent(&r.Data[0].Totals) + o, err := json.Marshal(r) + if err != nil { + log.Fatalf("failed to generate json: %v", err) + } + fmt.Printf(string(o)) +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/LICENSE b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/main.go b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/main.go new file mode 100644 index 0000000000000000000000000000000000000000..f351564034df276c774fb7a58b0a9c481e700b42 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/base-images/base-runner/gocoverage/pprof-merge/main.go @@ -0,0 +1,68 @@ +// Copyright 2019 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "flag" + "log" + "os" + + "github.com/google/pprof/profile" +) + +var ( + output string +) + +func main() { + flag.StringVar(&output, "o", "merged.data", "") + flag.Parse() + + files := os.Args[1:] + if len(files) == 0 { + log.Fatal("Give profiles files as arguments") + } + + var profiles []*profile.Profile + for _, fname := range files { + f, err := os.Open(fname) + if err != nil { + log.Fatalf("Cannot open profile file at %q: %v", fname, err) + } + p, err := profile.Parse(f) + if err != nil { + log.Fatalf("Cannot parse profile at %q: %v", fname, err) + } + profiles = append(profiles, p) + } + + merged, err := profile.Merge(profiles) + if err != nil { + log.Fatalf("Cannot merge profiles: %v", err) + } + + out, err := os.OpenFile(output, os.O_RDWR|os.O_CREATE, 0755) + if err != nil { + log.Fatalf("Cannot open output to write: %v", err) + } + + if err := merged.Write(out); err != nil { + log.Fatalf("Cannot write merged profile to file: %v", err) + } + + if err := out.Close(); err != nil { + log.Printf("Error when closing the output file: %v", err) + } +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..197aed2b02e4af2b3725040a5ce46f258337af82 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/actions/run_fuzzers/action.yml @@ -0,0 +1,82 @@ +# action.yml +name: 'run-fuzzers' +description: 'Runs fuzz target binaries for a specified length of time.' +inputs: + oss-fuzz-project-name: + description: 'The OSS-Fuzz project name.' + required: true + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + fuzz-seconds: + description: 'The total time allotted for fuzzing in seconds.' + required: true + default: 600 + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + sanitizer: + description: 'The sanitizer to run the fuzzers with.' + default: 'address' + mode: + description: | + The mode to run the fuzzers with ("code-change", "batch", "coverage", or "prune"). + "code-change" is for fuzzing a pull request or commit. + "batch" is for non-interactive fuzzing of an entire project. + "coverage" is for coverage generation. + "prune" is for corpus pruning. + required: false + default: 'code-change' + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + report-unreproducible-crashes: + description: 'If True, then unreproducible crashes will be reported.' + required: false + default: False + minimize-crashes: + description: 'If True, reportable crashes will be minimized.' + required: false + default: False + parallel-fuzzing: + description: "Whether to use all available cores for fuzzing." + required: false + default: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false + report-timeouts: + description: "Whether to report fails due to timeout." + required: false + default: true + report-ooms: + description: "Whether to report fails due to OOM." + required: false + default: true +runs: + using: 'docker' + image: '../../../run_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + FUZZ_SECONDS: ${{ inputs.fuzz-seconds }} + DRY_RUN: ${{ inputs.dry-run}} + SANITIZER: ${{ inputs.sanitizer }} + MODE: ${{ inputs.mode }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + REPORT_UNREPRODUCIBLE_CRASHES: ${{ inputs.report-unreproducible-crashes }} + MINIMIZE_CRASHES: ${{ inputs.minimize-crashes }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + PARALLEL_FUZZING: ${{ inputs.parallel-fuzzing }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} + REPORT_TIMEOUTS: ${{ inputs.report-timeouts }} + REPORT_OOMS: ${{ inputs.report-ooms}} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5b782e46d4d3116b628143666db8f3f6406ace0 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/external-actions/build_fuzzers/action.yml @@ -0,0 +1,75 @@ +# action.yml +name: 'build-fuzzers' +description: "Builds an OSS-Fuzz project's fuzzers." +inputs: + language: + description: 'Programming language project is written in.' + required: false + default: 'c++' + dry-run: + description: 'If set, run the action without actually reporting a failure.' + default: false + allowed-broken-targets-percentage: + description: 'The percentage of broken targets allowed in bad_build_check.' + required: false + sanitizer: + description: 'The sanitizer to build the fuzzers with.' + default: 'address' + project-src-path: + description: "The path to the project's source code checkout." + required: false + bad-build-check: + description: "Whether or not OSS-Fuzz's check for bad builds should be done." + required: false + default: true + keep-unaffected-fuzz-targets: + description: "Whether to keep unaffected fuzzers or delete them." + required: false + default: false + storage-repo: + description: | + The git repo to use for storing certain artifacts from fuzzing. + required: false + storage-repo-branch: + description: | + The branch of the git repo to use for storing certain artifacts from + fuzzing. + required: false + storage-repo-branch-coverage: + description: | + The branch of the git repo to use for storing coverage reports. + required: false + upload-build: + description: | + If set, will upload the build. + default: false + github-token: + description: | + Token for GitHub API. WARNING: THIS SHOULD NOT BE USED IN PRODUCTION YET + You should use "secrets.GITHUB_TOKEN" in your workflow file, do not + hardcode the token. + TODO(https://github.com/google/oss-fuzz/pull/5841#discussion_r639393361): + Document locking this down. + required: false + output-sarif: + description: "Whether to output fuzzing results to SARIF." + required: false + default: false +runs: + using: 'docker' + image: '../../../build_fuzzers.Dockerfile' + env: + OSS_FUZZ_PROJECT_NAME: ${{ inputs.oss-fuzz-project-name }} + LANGUAGE: ${{ inputs.language }} + DRY_RUN: ${{ inputs.dry-run}} + ALLOWED_BROKEN_TARGETS_PERCENTAGE: ${{ inputs.allowed-broken-targets-percentage}} + SANITIZER: ${{ inputs.sanitizer }} + PROJECT_SRC_PATH: ${{ inputs.project-src-path }} + GITHUB_TOKEN: ${{ inputs.github-token }} + LOW_DISK_SPACE: 'True' + BAD_BUILD_CHECK: ${{ inputs.bad-build-check }} + UPLOAD_BUILD: ${{ inputs.upload-build }} + CIFUZZ_DEBUG: 'True' + CFL_PLATFORM: 'github' + KEEP_UNAFFECTED_FUZZ_TARGETS: ${{ inputs.keep-unaffected-fuzz-targets }} + OUTPUT_SARIF: ${{ inputs.output-sarif }} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddea132661e3acae27eb5abff61f1432eb65ba5 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/filesystem/__init__.py @@ -0,0 +1,107 @@ +# Copyright 2022 Google LLC +# +# 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. +"""Filestore implementation using a filesystem directory.""" +import logging +import os +import shutil +import subprocess +import sys + +from distutils import dir_util + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore + + +def recursive_list_dir(directory): + """Returns list of all files in |directory|, including those in + subdirectories.""" + files = [] + for root, _, filenames in os.walk(directory): + for filename in filenames: + files.append(os.path.join(root, filename)) + return files + + +class FilesystemFilestore(filestore.BaseFilestore): + """Filesystem implementation using a filesystem directory.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._filestore_root_dir = self.config.platform_conf.filestore_root_dir + + def _get_filestore_path(self, name, prefix_dir): + """Returns the filesystem path in the filestore for |name| and + |prefix_dir|.""" + return os.path.join(self._filestore_root_dir, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + filestore_path = self._get_filestore_path(name, prefix) + if os.path.exists(filestore_path): + initial_files = set(recursive_list_dir(filestore_path)) + else: + initial_files = set() + + # Make directory and any parents. + os.makedirs(filestore_path, exist_ok=True) + copied_files = set(dir_util.copy_tree(directory, filestore_path)) + if not delete: + return True + + files_to_delete = initial_files - copied_files + for file_path in files_to_delete: + os.remove(file_path) + return True + + def _download_directory(self, name, dst_directory, prefix): + filestore_path = self._get_filestore_path(name, prefix) + return dir_util.copy_tree(filestore_path, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, directory, self.CRASHES_DIR) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py new file mode 100644 index 0000000000000000000000000000000000000000..56be23bacd0fdf75c5f9bf7fb0fe475a2d48b6b6 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/git/git_test.py @@ -0,0 +1,122 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Tests for git.""" +import filecmp +import os +import tempfile +import subprocess +import sys +import unittest +from unittest import mock + +# pylint: disable=wrong-import-position +INFRA_DIR = os.path.dirname( + os.path.dirname(os.path.dirname(os.path.dirname( + os.path.abspath(__file__))))) +sys.path.append(INFRA_DIR) + +from filestore import git +import test_helpers + +# pylint: disable=protected-access,no-self-use + + +class GitFilestoreTest(unittest.TestCase): + """Tests for GitFilestore.""" + + def setUp(self): + self.git_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.git_dir.cleanup) + + self.local_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.local_dir.cleanup) + + self.download_dir = tempfile.TemporaryDirectory() + self.addCleanup(self.download_dir.cleanup) + + with open(os.path.join(self.local_dir.name, 'a'), 'w') as handle: + handle.write('') + + os.makedirs(os.path.join(self.local_dir.name, 'b')) + + with open(os.path.join(self.local_dir.name, 'b', 'c'), 'w') as handle: + handle.write('') + + self.git_repo = git.git_runner(self.git_dir.name) + self.git_repo('init', '--bare') + + self.config = test_helpers.create_run_config( + git_store_repo='file://' + self.git_dir.name, + git_store_branch='main', + git_store_branch_coverage='cov-branch') + + self.mock_ci_filestore = mock.MagicMock() + self.git_store = git.GitFilestore(self.config, self.mock_ci_filestore) + + def assert_dirs_same(self, first, second): + """Asserts two dirs are the same.""" + dcmp = filecmp.dircmp(first, second) + if dcmp.diff_files or dcmp.left_only or dcmp.right_only: + return False + + return all( + self.assert_dirs_same(os.path.join(first, subdir), + os.path.join(second, subdir)) + for subdir in dcmp.common_dirs) + + def get_repo_filelist(self, branch): + """Get files in repo.""" + return subprocess.check_output([ + 'git', '-C', self.git_dir.name, 'ls-tree', '-r', '--name-only', branch + ]).decode().splitlines() + + def test_upload_download_corpus(self): + """Tests uploading and downloading corpus.""" + self.git_store.upload_corpus('target', self.local_dir.name) + self.git_store.download_corpus('target', self.download_dir.name) + self.assert_dirs_same(self.local_dir.name, self.download_dir.name) + + self.assertCountEqual([ + 'corpus/target/a', + 'corpus/target/b/c', + ], self.get_repo_filelist('main')) + + def test_upload_download_coverage(self): + """Tests uploading and downloading corpus.""" + self.git_store.upload_coverage('latest', self.local_dir.name) + self.git_store.download_coverage('latest', self.download_dir.name) + self.assert_dirs_same(self.local_dir.name, self.download_dir.name) + + self.assertCountEqual([ + 'coverage/latest/a', + 'coverage/latest/b/c', + ], self.get_repo_filelist('cov-branch')) + + def test_upload_crashes(self): + """Tests uploading crashes.""" + self.git_store.upload_crashes('current', self.local_dir.name) + self.mock_ci_filestore.upload_crashes.assert_called_with( + 'current', self.local_dir.name) + + def test_upload_build(self): + """Tests uploading build.""" + self.git_store.upload_build('sanitizer', self.local_dir.name) + self.mock_ci_filestore.upload_build.assert_called_with( + 'sanitizer', self.local_dir.name) + + def test_download_build(self): + """Tests downloading build.""" + self.git_store.download_build('sanitizer', self.download_dir.name) + self.mock_ci_filestore.download_build.assert_called_with( + 'sanitizer', self.download_dir.name) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py new file mode 100644 index 0000000000000000000000000000000000000000..35e92eafb2cf64159c372721598e2a084a573ad4 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/github_actions/github_api.py @@ -0,0 +1,109 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Module for dealing with the GitHub API. This is different from +github_actions_toolkit which only deals with the actions API. We need to use +both.""" +import logging +import os +import sys + +import requests + +import filestore + +# pylint: disable=wrong-import-position,import-error + +sys.path.append( + os.path.join(__file__, os.path.pardir, os.path.pardir, os.path.pardir, + os.path.pardir)) +import retry + +_MAX_ITEMS_PER_PAGE = 100 + +_GET_ATTEMPTS = 3 +_GET_BACKOFF = 1 + + +def get_http_auth_headers(config): + """Returns HTTP headers for authentication to the API.""" + authorization = f'token {config.token}' + return { + 'Authorization': authorization, + 'Accept': 'application/vnd.github.v3+json' + } + + +def _get_artifacts_list_api_url(repo_owner, repo_name): + """Returns the artifacts_api_url for |repo_name| owned by |repo_owner|.""" + github_api_url = os.getenv('GITHUB_API_URL', 'https://api.github.com') + return (f'{github_api_url}/repos/{repo_owner}/' + f'{repo_name}/actions/artifacts') + + +@retry.wrap(_GET_ATTEMPTS, _GET_BACKOFF) +def _do_get_request(*args, **kwargs): + """Wrapped version of requests.get that does retries.""" + return requests.get(*args, **kwargs) + + +def _get_items(url, headers): + """Generator that gets and yields items from a GitHub API endpoint (specified + by |URL|) sending |headers| with the get request.""" + # Github API response pages are 1-indexed. + page_counter = 1 + + # Set to infinity so we run loop at least once. + total_num_items = float('inf') + + item_num = 0 + while item_num < total_num_items: + params = {'per_page': _MAX_ITEMS_PER_PAGE, 'page': str(page_counter)} + response = _do_get_request(url, params=params, headers=headers) + response_json = response.json() + if not response.status_code == 200: + # Check that request was successful. + logging.error('Request to %s failed. Code: %d. Response: %s', + response.request.url, response.status_code, response_json) + raise filestore.FilestoreError('Github API request failed.') + + if total_num_items == float('inf'): + # Set proper total_num_items + total_num_items = response_json['total_count'] + + # Get the key for the items we are after. + keys = [key for key in response_json.keys() if key != 'total_count'] + assert len(keys) == 1, keys + items_key = keys[0] + + for item in response_json[items_key]: + yield item + item_num += 1 + + page_counter += 1 + + +def find_artifact(artifact_name, artifacts): + """Find the artifact with the name |artifact_name| in |artifacts|.""" + for artifact in artifacts: + # TODO(metzman): Handle multiple by making sure we download the latest. + if artifact['name'] == artifact_name and not artifact['expired']: + return artifact + return None + + +def list_artifacts(owner, repo, headers): + """Returns a generator of all the artifacts for |owner|/|repo|.""" + url = _get_artifacts_list_api_url(owner, repo) + logging.debug('Getting artifacts from: %s', url) + return _get_items(url, headers) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..43ee0ce8f17a4231bb46f41377d1277cb87a854b --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gitlab/__init__.py @@ -0,0 +1,133 @@ +# Copyright 2022 Google LLC +# +# 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. +"""GitLab filestore implementation.""" +import logging + +import json +import os +import shutil +import tempfile + +import filestore +import http_utils + +# pylint: disable=no-self-use,unused-argument + + +class GitlabFilestore(filestore.BaseFilestore): + """Implementation of BaseFilestore using GitLab. + Needs a cache to upload and download builds. + Needs a git repository for corpus and coverage. + """ + + BUILD_PREFIX = 'build-' + CORPUS_PREFIX = 'corpus-' + COVERAGE_PREFIX = 'coverage-' + CRASHES_PREFIX = 'crashes-' + + def __init__(self, config): + super().__init__(config) + self.artifacts_dir = self.config.platform_conf.artifacts_dir + self.cache_dir = self.config.platform_conf.cache_dir + if self.config.git_store_repo: + self.git_filestore = filestore.git.GitFilestore(config, None) + else: + self.git_filestore = None + + def upload_crashes(self, name, directory): + """GitLab artifacts implementation of upload_crashes.""" + # Upload crashes as job artifacts. + if os.listdir(directory): + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.CRASHES_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def upload_corpus(self, name, directory, replace=False): + """GitLab artifacts implementation of upload_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.upload_corpus(name, directory, replace) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + # Remove previous corpus from cache if any. + shutil.rmtree(dest_dir_cache, ignore_errors=True) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_build(self, name, directory): + """GitLab artifacts implementation of upload_build.""" + # Puts build into the cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + + def upload_coverage(self, name, directory): + """GitLab artifacts implementation of upload_coverage.""" + # Use the git filestore. + if self.git_filestore: + self.git_filestore.upload_coverage(name, directory) + return + # Fall back to cache. + dest_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + logging.info('Copying from %s to cache %s.', directory, dest_dir_cache) + shutil.copytree(directory, dest_dir_cache, dirs_exist_ok=True) + # And also updates coverage reports as artifacts + # as it should not be too big. + dest_dir_artifacts = os.path.join(self.config.project_src_path, + self.artifacts_dir, + self.COVERAGE_PREFIX + name) + logging.info('Uploading artifacts to %s.', dest_dir_artifacts) + shutil.copytree(directory, dest_dir_artifacts) + + def _copy_from_cache(self, src_dir_cache, dst_directory): + if not os.path.exists(src_dir_cache): + logging.info('Cache %s does not exist.', src_dir_cache) + return False + logging.info('Copying %s from cache to %s.', src_dir_cache, dst_directory) + shutil.copytree(src_dir_cache, dst_directory, dirs_exist_ok=True) + return True + + def download_corpus(self, name, dst_directory): + """GitLab artifacts implementation of download_corpus.""" + # Use the git filestore if any. + if self.git_filestore: + self.git_filestore.download_corpus(name, dst_directory) + return + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.CORPUS_PREFIX + name) + self._copy_from_cache(src_dir_cache, dst_directory) + + def download_build(self, name, dst_directory): + """GitLab artifacts implementation of download_build.""" + # Gets build from the cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.BUILD_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) + + def download_coverage(self, name, dst_directory): + """GitLab artifacts implementation of download_coverage.""" + # Use the git filestore if any. + if self.git_filestore: + return self.git_filestore.download_coverage(name, dst_directory) + # Fall back to cache. + src_dir_cache = os.path.join(self.config.project_src_path, self.cache_dir, + self.COVERAGE_PREFIX + name) + return self._copy_from_cache(src_dir_cache, dst_directory) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85f85508d78e8a01d11dcbed7c3f463d830d322b --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/gsutil/__init__.py @@ -0,0 +1,109 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Filestore implementation using gsutil.""" +import logging +import os +import posixpath +import subprocess +import sys + +# pylint: disable=wrong-import-position,import-error +sys.path.append( + os.path.join(os.path.dirname(os.path.abspath(__file__)), os.pardir, + os.pardir, os.pardir)) +import filestore +import utils + + +def _gsutil_execute(*args, parallel=True): + """Executes a gsutil command, passing |*args| to gsutil and returns the + stdout, stderr and returncode. Exceptions on failure.""" + command = ['gsutil'] + if parallel: + command.append('-m') + command += list(args) + logging.info('Executing gsutil command: %s', command) + return utils.execute(command, check_result=True) + + +def _rsync(src, dst, recursive=True, delete=False): + """Executes gsutil rsync on |src| and |dst|""" + args = ['rsync'] + if recursive: + args.append('-r') + if delete: + args.append('-d') + args += [src, dst] + return _gsutil_execute(*args) + + +class GSUtilFilestore(filestore.BaseFilestore): + """Filestore implementation using gsutil.""" + BUILD_DIR = 'build' + CRASHES_DIR = 'crashes' + CORPUS_DIR = 'corpus' + COVERAGE_DIR = 'coverage' + + def __init__(self, config): + super().__init__(config) + self._cloud_bucket = self.config.cloud_bucket + + def _get_gsutil_url(self, name, prefix_dir): + """Returns the gsutil URL for |name| and |prefix_dir|.""" + if not prefix_dir: + return posixpath.join(self._cloud_bucket, name) + return posixpath.join(self._cloud_bucket, prefix_dir, name) + + def _upload_directory(self, name, directory, prefix, delete=False): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(directory, gsutil_url, delete=delete) + + def _download_directory(self, name, dst_directory, prefix): + gsutil_url = self._get_gsutil_url(name, prefix) + return _rsync(gsutil_url, dst_directory) + + def upload_crashes(self, name, directory): + """Uploads the crashes at |directory| to |name|.""" + # Name is going to be "current". I don't know if this makes sense outside of + # GitHub Actions. + gsutil_url = self._get_gsutil_url(name, self.CRASHES_DIR) + logging.info('Uploading crashes to %s.', gsutil_url) + return _rsync(directory, gsutil_url) + + def upload_corpus(self, name, directory, replace=False): + """Uploads the crashes at |directory| to |name|.""" + return self._upload_directory(name, + directory, + self.CORPUS_DIR, + delete=replace) + + def upload_build(self, name, directory): + """Uploads the build located at |directory| to |name|.""" + return self._upload_directory(name, directory, self.BUILD_DIR) + + def upload_coverage(self, name, directory): + """Uploads the coverage report at |directory| to |name|.""" + return self._upload_directory(name, directory, self.COVERAGE_DIR) + + def download_corpus(self, name, dst_directory): + """Downloads the corpus located at |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.CORPUS_DIR) + + def download_build(self, name, dst_directory): + """Downloads the build with |name| to |dst_directory|.""" + return self._download_directory(name, dst_directory, self.BUILD_DIR) + + def download_coverage(self, name, dst_directory): + """Downloads the latest project coverage report.""" + return self._download_directory(name, dst_directory, self.COVERAGE_DIR) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2d063116ebcffcf2552225a58a824e4e4409be49 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/filestore/no_filestore/__init__.py @@ -0,0 +1,51 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Empty filestore implementation for platforms that haven't implemented it.""" +import logging + +import filestore + +# pylint:disable=no-self-use,unused-argument + + +class NoFilestore(filestore.BaseFilestore): + """Empty Filestore implementation.""" + + def upload_crashes(self, name, directory): + """Noop implementation of upload_crashes.""" + logging.info('Not uploading crashes because no Filestore.') + + def upload_corpus(self, name, directory, replace=False): + """Noop implementation of upload_corpus.""" + logging.info('Not uploading corpus because no Filestore.') + + def upload_build(self, name, directory): + """Noop implementation of upload_build.""" + logging.info('Not uploading build because no Filestore.') + + def upload_coverage(self, name, directory): + """Noop implementation of upload_coverage.""" + logging.info('Not uploading coverage because no Filestore.') + + def download_corpus(self, name, dst_directory): + """Noop implementation of download_corpus.""" + logging.info('Not downloading corpus because no Filestore.') + + def download_build(self, name, dst_directory): + """Noop implementation of download_build.""" + logging.info('Not downloading build because no Filestore.') + + def download_coverage(self, name, dst_directory): + """Noop implementation of download_coverage.""" + logging.info('Not downloading coverage because no Filestore.') diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py new file mode 100644 index 0000000000000000000000000000000000000000..75b26f526a4f887383afa122e668d2a6010ff606 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/platform_config/platform_config_test.py @@ -0,0 +1,82 @@ +# Copyright 2021 Google LLC +# +# 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. +"""Tests for platform_config.""" +import os +import unittest + +import platform_config +import test_helpers + + +class GetProjectRepoOwnerAndNameTest(unittest.TestCase): + """Tests for get_project_repo_owner and get_project_repo_name.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.repo_owner = 'repo-owner' + self.repo_name = 'repo-name' + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertIsNone(self.env.project_repo_name) + + def test_owner(self): + """Tests that the correct result is returned for owner.""" + self.assertIsNone(self.env.project_repo_owner) + + def test_empty_repository(self): + """Tests that the correct result is returned when repository is an empty + string.""" + os.environ['REPOSITORY'] = '' + self.assertEqual(self.env.project_repo_name, '') + + def test_repository(self): + """Tests that the correct result is returned when repository contains the + just the repo name (as it does outside of GitHub).""" + os.environ['REPOSITORY'] = self.repo_name + self.assertEqual(self.env.project_repo_name, self.repo_name) + + +class ProjectSrcPathTest(unittest.TestCase): + """Tests for project_src_path.""" + + def setUp(self): + test_helpers.patch_environ(self) + + def test_not_github(self): + """Tests that project_src_path returns the correct result not on + GitHub.""" + project_src_path = 'project-src' + os.environ['PROJECT_SRC_PATH'] = project_src_path + generic_ci_env = platform_config.BasePlatformConfig() + self.assertEqual(generic_ci_env.project_src_path, project_src_path) + + +class GetGitUrlTest(unittest.TestCase): + """Tests for BasePlatformConfig.git_url.""" + + def setUp(self): + test_helpers.patch_environ(self) + self.env = platform_config.BasePlatformConfig() + + def test_unset_repository(self): + """Tests that the correct result is returned when repository is not set.""" + self.assertEqual(self.env.git_url, None) + + def test_repository(self): + """Tests that the correct result is returned when GITHUB_REPOSITORY is + set.""" + os.environ['GITHUB_REPOSITORY'] = 'repo/owner' + self.assertIsNone(self.env.git_url) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt new file mode 100644 index 0000000000000000000000000000000000000000..8caebad0cbf1d7778b7d7ea0346410ba012f8acd --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/example_crash_fuzzer_bug_summary.txt @@ -0,0 +1,68 @@ +AddressSanitizer: heap-buffer-overflow on address 0x62500001b530 at pc 0x00000052138a bp 0x7ffe62db2c10 sp 0x7ffe62db23d8 +READ of size 52 at 0x62500001b530 thread T0 +SCARINESS: 26 (multi-byte-read-heap-buffer-overflow) + #0 0x521389 in __asan_memcpy /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 + #1 0x567590 in yr_object_set_string /src/yara/libyara/object.c:1122:5 + #2 0x5afced in dex_parse /src/yara/libyara/modules/dex/dex.c:781:5 + #3 0x5b4a8b in dex__load /src/yara/libyara/modules/dex/dex.c:1218:7 + #4 0x56537c in yr_modules_load /src/yara/libyara/modules.c:179:16 + #5 0x5d6583 in yr_execute_code /src/yara/libyara/exec.c:1276:18 + #6 0x56f5c0 in yr_scanner_scan_mem_blocks /src/yara/libyara/scanner.c:444:3 + #7 0x56bf23 in yr_rules_scan_mem_blocks /src/yara/libyara/rules.c:235:12 + #8 0x56c182 in yr_rules_scan_mem /src/yara/libyara/rules.c:285:10 + #9 0x5548d2 in LLVMFuzzerTestOneInput /src/yara/tests/oss-fuzz/dex_fuzzer.cc:40:3 + #10 0x45a3b1 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:556:15 + #11 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #12 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #13 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #14 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #15 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #16 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + #17 0x41e348 in _start (out/dex_fuzzer+0x41e348) + +0x62500001b530 is located 0 bytes to the right of 9264-byte region [0x625000019100,0x62500001b530) +allocated by thread T0 here: + #0 0x521f4d in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:145:3 + #1 0x4331b7 in operator new(unsigned long) (out/dex_fuzzer+0x4331b7) + #2 0x459ad5 in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:470:3 + #3 0x45be77 in fuzzer::Fuzzer::MutateAndTestOne() /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:698:19 + #4 0x45cc05 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:830:5 + #5 0x44ac88 in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:824:6 + #6 0x474ab2 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:19:10 + #7 0x7f4409b7a82f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f) + +SUMMARY: AddressSanitizer: heap-buffer-overflow /src/llvm-project/compiler-rt/lib/asan/asan_interceptors_memintrinsics.cpp:22:3 in __asan_memcpy +Shadow bytes around the buggy address: + 0x0c4a7fffb650: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb660: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb670: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb680: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 + 0x0c4a7fffb690: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 +=>0x0c4a7fffb6a0: 00 00 00 00 00 00[fa]fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6b0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c4a7fffb6f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb + Shadow gap: cc +==12==ABORTING \ No newline at end of file diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..2c52ef90f4cf6ea50746586d7f5c0ffdc5291435 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/.clusterfuzzlite/build.sh @@ -0,0 +1,24 @@ +#!/bin/bash -eu +# Copyright 2020 Google Inc. +# +# 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. +# +################################################################################ + +make clean # Not strictly necessary, since we are building in a fresh dir. +make -j$(nproc) all # Build the fuzz targets. + +# Copy the fuzzer executables, zip-ed corpora, option and dictionary files to $OUT +find . -name '*_fuzzer' -exec cp -v '{}' $OUT ';' +find . -name '*_fuzzer.dict' -exec cp -v '{}' $OUT ';' # If you have dictionaries. +find . -name '*_fuzzer.options' -exec cp -v '{}' $OUT ';' # If you have custom options. diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..2c177377627adacda8eda47a1f13830cb1f3998b --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/Makefile @@ -0,0 +1,44 @@ +# Copyright 2017 Google Inc. All Rights Reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); + +# Simple example of a build file that nicely integrates a fuzz target +# with the rest of the project. +# +# We use 'make' as the build system, but these ideas are applicable +# to any other build system + +# By default, use our own standalone_fuzz_target_runner. +# This runner does no fuzzing, but simply executes the inputs +# provided via parameters. +# Run e.g. "make all LIB_FUZZING_ENGINE=/path/to/libFuzzer.a" +# to link the fuzzer(s) against a real fuzzing engine. +# +# OSS-Fuzz will define its own value for LIB_FUZZING_ENGINE. +LIB_FUZZING_ENGINE ?= standalone_fuzz_target_runner.o + +# Values for CC, CFLAGS, CXX, CXXFLAGS are provided by OSS-Fuzz. +# Outside of OSS-Fuzz use the ones you prefer or rely on the default values. +# Do not use the -fsanitize=* flags by default. +# OSS-Fuzz will use different -fsanitize=* flags for different builds (asan, ubsan, msan, ...) + +# You may add extra compiler flags like this: +CXXFLAGS += -std=c++11 + +all: do_stuff_fuzzer + +clean: + rm -fv *.a *.o *_fuzzer crash-* *.zip + +# Fuzz target, links against $LIB_FUZZING_ENGINE, so that +# you may choose which fuzzing engine to use. +do_stuff_fuzzer: do_stuff_fuzzer.cpp my_api.a standalone_fuzz_target_runner.o + ${CXX} ${CXXFLAGS} $< my_api.a ${LIB_FUZZING_ENGINE} -o $@ + + +# The library itself. +my_api.a: my_api.cpp my_api.h + ${CXX} ${CXXFLAGS} $< -c + ar ruv my_api.a my_api.o + +# The standalone fuzz target runner. +standalone_fuzz_target_runner.o: standalone_fuzz_target_runner.cpp diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict new file mode 100644 index 0000000000000000000000000000000000000000..6a82ac4b3aa09ea8bbe6fc127e1bad4ed1c28ebb --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/do_stuff_fuzzer.dict @@ -0,0 +1,6 @@ +# A dictionary for more efficient fuzzing of DoStuff(). +# If the inputs contain multi-byte tokens, list them here. +# See https://llvm.org/docs/LibFuzzer.html#dictionaries +"foo" +"bar" +"ouch" diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9a2c1bc1c0d8a7d1a2473e0563b1a385b11ed621 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.cpp @@ -0,0 +1,36 @@ +// Copyright 2020 Google LLC +// +// 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. + +// Implementation of "my_api". +#include "my_api.h" + +#include + +// Do some computations with 'str', return the result. +// This function contains a bug. Can you spot it? +size_t DoStuff(const std::string &str) { + std::vector Vec({0, 1, 2, 3, 4}); + size_t Idx = 0; + if (str.size() > 5) + Idx++; + if (str.find("foo") != std::string::npos) + Idx++; + if (str.find("bar") != std::string::npos) + Idx++; + if (str.find("ouch") != std::string::npos) + Idx++; + if (str.find("omg") != std::string::npos) + Idx++; + return Vec[Idx]; +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h new file mode 100644 index 0000000000000000000000000000000000000000..325aa15ccc7f6fbed196437aeb75c94a88a630a6 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/my_api.h @@ -0,0 +1,19 @@ +// Copyright 2020 Google LLC +// +// 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. + +// A library that does ... stuff. +// Serves as an example of good fuzz testing and OSS-Fuzz integration. +#include + +size_t DoStuff(const std::string &str); diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38a0454f0ac98e74052670c5eac9e5a86df9dfc7 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/external-project/standalone_fuzz_target_runner.cpp @@ -0,0 +1,47 @@ +// Copyright 2020 Google LLC +// +// 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. + +// Example of a standalone runner for "fuzz targets". +// It reads all files passed as parameters and feeds their contents +// one by one into the fuzz target (LLVMFuzzerTestOneInput). +// This runner does not do any fuzzing, but allows us to run the fuzz target +// on the test corpus (e.g. "do_stuff_test_data") or on a single file, +// e.g. the one that comes from a bug report. + +#include +#include +#include +#include + +// Forward declare the "fuzz target" interface. +// We deliberately keep this inteface simple and header-free. +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); + +int main(int argc, char **argv) { + for (int i = 1; i < argc; i++) { + std::ifstream in(argv[i]); + in.seekg(0, in.end); + size_t length = in.tellg(); + in.seekg (0, in.beg); + std::cout << "Reading " << length << " bytes from " << argv[i] << std::endl; + // Allocate exactly length bytes so that we reliably catch buffer overflows. + std::vector bytes(length); + in.read(bytes.data(), bytes.size()); + assert(in); + LLVMFuzzerTestOneInput(reinterpret_cast(bytes.data()), + bytes.size()); + std::cout << "Execution successful" << std::endl; + } + return 0; +} diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt new file mode 100644 index 0000000000000000000000000000000000000000..71f6e29ad3bf104ca54293b7395f3c0057c205a0 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/cifuzz/test_data/sarif_utils_only_llvmfuzzer_stack.txt @@ -0,0 +1,302 @@ +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82577 inline 8-bit counters): 82573 [0x7fc55e6bedf0, 0x7fc55e6d307d), 4 [0x5e9c28, 0x5e9c2c), +2023-05-04 01:02:55,065 - root - INFO - Not reporting crash in fuzz-bus-label because process timed out. +2023-05-04 01:02:55,069 - root - INFO - Deleting corpus and seed corpus of fuzz-bus-label to save disk. +INFO: Loaded 2 PC tables (82577 PCs): 82573 [0x7fc55e6d3080,0x7fc55e815950), 4 [0x5a6c78,0x5a6cb8), +INFO: 256 files found in /github/workspace/cifuzz-corpus/fuzz-bus-label +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 256 min: 1b max: 5242880b total: 30968483b rss: 48Mb +#257 INITED cov: 41 ft: 230 corp: 111/4360b exec/s: 0 rss: 73Mb +#131072 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#262144 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 76Mb +#524288 pulse cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43690 rss: 77Mb +#609082 DONE cov: 41 ft: 230 corp: 111/4360b lim: 1048576 exec/s: 43505 rss: 77Mb +Done 609082 runs in 14 second(s) +stat::number_of_executed_units: 609082 +stat::average_exec_per_sec: 43505 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 77 +/github/workspace/build-out/fuzz-bus-label -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpsngf52cy/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bus-label >fuzz-1.log 2>&1 +2023-05-04 01:02:55,082 - root - INFO - Deleting fuzz target: fuzz-bus-label. +2023-05-04 01:02:55,083 - root - INFO - Done deleting. +2023-05-04 01:02:55,084 - root - INFO - Fuzzer fuzz-bus-label finished running without reportable crashes. +2023-05-04 01:02:55,084 - root - INFO - Running fuzzer: fuzz-dhcp-server. +2023-05-04 01:02:55,085 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip +2023-05-04 01:02:55,088 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:02:55,145 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-dhcp-server/public.zip HTTP/1.1" 200 806749 +2023-05-04 01:02:55,350 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83640 inline 8-bit counters): 82573 [0x7fe86ff70df0, 0x7fe86ff8507d), 1067 [0x60c638, 0x60ca63), +INFO: Loaded 2 PC tables (83640 PCs): 82573 [0x7fe86ff85080,0x7fe8700c7950), 1067 [0x60ca68,0x610d18), +INFO: 1153 files found in /github/workspace/cifuzz-corpus/fuzz-dhcp-server +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 1048576 bytes +INFO: seed corpus: files: 1153 min: 1b max: 5242879b total: 17056071b rss: 50Mb +#1155 INITED cov: 577 ft: 1116 corp: 203/54Kb exec/s: 0 rss: 86Mb +#1167 NEW cov: 577 ft: 1117 corp: 204/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeASCIIInt-CrossOver- +#1509 NEW cov: 577 ft: 1118 corp: 205/54Kb lim: 1048576 exec/s: 0 rss: 86Mb L: 243/1071 MS: 2 ChangeBit-CopyPart- +#63018 NEW cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21006 rss: 86Mb L: 245/1071 MS: 4 InsertByte-ChangeByte-CMP-InsertByte- DE: "2\000\000\000\000\000\000\000"- +#65536 pulse cov: 577 ft: 1119 corp: 206/55Kb lim: 1048576 exec/s: 21845 rss: 86Mb +Loaded 1024/1155 files from /github/workspace/cifuzz-corpus/fuzz-dhcp-server +#99784 NEW cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19956 rss: 105Mb L: 243/1071 MS: 2 ChangeASCIIInt-ChangeBinInt- +#131072 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 21845 rss: 105Mb +#262144 pulse cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 20164 rss: 105Mb +#275639 DONE cov: 577 ft: 1120 corp: 207/55Kb lim: 1048576 exec/s: 19688 rss: 105Mb +###### Recommended dictionary. ###### +"2\000\000\000\000\000\000\000" # Uses: 17879 +###### End of recommended dictionary. ###### +Done 275639 runs in 14 second(s) +stat::number_of_executed_units: 275639 +stat::average_exec_per_sec: 19688 +stat::new_units_added: 4 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 105 +/github/workspace/build-out/fuzz-dhcp-server -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpyxgwwsvr/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-dhcp-server >fuzz-1.log 2>&1 +2023-05-04 01:03:18,374 - root - INFO - Not reporting crash in fuzz-dhcp-server because process timed out. +2023-05-04 01:03:18,377 - root - INFO - Deleting corpus and seed corpus of fuzz-dhcp-server to save disk. +2023-05-04 01:03:18,399 - root - INFO - Deleting fuzz target: fuzz-dhcp-server. +2023-05-04 01:03:18,400 - root - INFO - Done deleting. +2023-05-04 01:03:18,400 - root - INFO - Fuzzer fuzz-dhcp-server finished running without reportable crashes. +2023-05-04 01:03:18,401 - root - INFO - Running fuzzer: fuzz-bcd. +2023-05-04 01:03:18,401 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip +2023-05-04 01:03:18,404 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:18,582 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-bcd/public.zip HTTP/1.1" 200 2293254 +2023-05-04 01:03:18,804 - root - INFO - Starting fuzzing +Fuzzing logs: +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-0.log 2>&1 +================== Job 0 exited with exit code 0 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (83175 inline 8-bit counters): 82573 [0x7f1b5387edf0, 0x7f1b5389307d), 602 [0x5f8718, 0x5f8972), +INFO: Loaded 2 PC tables (83175 PCs): 82573 [0x7f1b53893080,0x7f1b539d5950), 602 [0x5f8978,0x5faf18), +INFO: 1260 files found in /github/workspace/cifuzz-corpus/fuzz-bcd +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 946175 bytes +INFO: seed corpus: files: 1260 min: 1b max: 946175b total: 10373697b rss: 48Mb +#1261 INITED cov: 137 ft: 653 corp: 282/1416Kb exec/s: 0 rss: 91Mb +#65536 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#131072 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 32768 rss: 98Mb +#262144 pulse cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 37449 rss: 98Mb +#475081 DONE cov: 137 ft: 653 corp: 282/1416Kb lim: 946175 exec/s: 33934 rss: 98Mb +Done 475081 runs in 14 second(s) +stat::number_of_executed_units: 475081 +stat::average_exec_per_sec: 33934 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 98 +/github/workspace/build-out/fuzz-bcd -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpgvqlyr8q/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-bcd >fuzz-1.log 2>&1 +2023-05-04 01:03:41,821 - root - INFO - Not reporting crash in fuzz-bcd because process timed out. +2023-05-04 01:03:41,822 - root - INFO - Deleting corpus and seed corpus of fuzz-bcd to save disk. +2023-05-04 01:03:41,848 - root - INFO - Deleting fuzz target: fuzz-bcd. +2023-05-04 01:03:41,848 - root - INFO - Done deleting. +2023-05-04 01:03:41,848 - root - INFO - Fuzzer fuzz-bcd finished running without reportable crashes. +2023-05-04 01:03:41,848 - root - INFO - Running fuzzer: fuzz-varlink. +2023-05-04 01:03:41,849 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip +2023-05-04 01:03:41,852 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:03:41,906 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-varlink/public.zip HTTP/1.1" 200 2586434 +2023-05-04 01:03:42,671 - root - INFO - Starting fuzzing +2023-05-04 01:04:05,709 - root - INFO - Not reporting crash in fuzz-varlink because process timed out. +Fuzzing logs: +/github/workspace/build-out/fuzz-varlink -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpbtf4f932/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-varlink >fuzz-0.log 2>&1 +2023-05-04 01:04:05,709 - root - INFO - Deleting corpus and seed corpus of fuzz-varlink to save disk. +2023-05-04 01:04:05,806 - root - INFO - Deleting fuzz target: fuzz-varlink. +2023-05-04 01:04:05,806 - root - INFO - Done deleting. +2023-05-04 01:04:05,806 - root - INFO - Fuzzer fuzz-varlink finished running without reportable crashes. +2023-05-04 01:04:05,806 - root - INFO - Running fuzzer: fuzz-unit-file. +2023-05-04 01:04:05,807 - root - INFO - Downloading corpus from OSS-Fuzz: https://storage.googleapis.com/systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip +2023-05-04 01:04:05,809 - urllib3.connectionpool - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443 +2023-05-04 01:04:05,897 - urllib3.connectionpool - DEBUG - https://storage.googleapis.com:443 "GET /systemd-backup.clusterfuzz-external.appspot.com/corpus/libFuzzer/systemd_fuzz-unit-file/public.zip HTTP/1.1" 200 4999974 +2023-05-04 01:04:07,869 - root - INFO - Starting fuzzing +2023-05-04 01:04:09,516 - root - INFO - Fuzzer: fuzz-unit-file. Detected bug. +Fuzzing logs: +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-0.log 2>&1 +2023-05-04 01:04:09,517 - root - INFO - Trying to reproduce crash using: /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03. +================== Job 0 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7f3b0de4cdf0, 0x7f3b0de6107d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7f3b0de61080,0x7f3b0dfa3950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==74==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7fffeea64fe0 sp 0x7fffeea64fd8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7f3b0ce20082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in LLVMFuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==74==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 67 +/github/workspace/build-out/fuzz-unit-file -timeout=25 -rss_limit_mb=2560 -len_control=0 -seed=1337 -artifact_prefix=/tmp/tmpjhswtxiw/ -max_total_time=13 -print_final_stats=1 /github/workspace/cifuzz-corpus/fuzz-unit-file >fuzz-1.log 2>&1 +================== Job 1 exited with exit code 77 ============ +INFO: Running with entropic power schedule (0xFF, 100). +INFO: Seed: 1337 +INFO: Loaded 2 modules (82576 inline 8-bit counters): 82573 [0x7ff1ba038df0, 0x7ff1ba04d07d), 3 [0x5e9b28, 0x5e9b2b), +INFO: Loaded 2 PC tables (82576 PCs): 82573 [0x7ff1ba04d080,0x7ff1ba18f950), 3 [0x5a6af8,0x5a6b28), +INFO: 20907 files found in /github/workspace/cifuzz-corpus/fuzz-unit-file +INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 604973 bytes +INFO: seed corpus: files: 20907 min: 1b max: 604973b total: 16005340b rss: 61Mb +================================================================= +==78==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x602000005078 at pc 0x0000004ddffa bp 0x7ffc2e6825c0 sp 0x7ffc2e6825b8 +READ of size 4 at 0x602000005078 thread T0 +SCARINESS: 27 (4-byte-read-heap-buffer-overflow-far-from-bounds) + #0 0x4ddff9 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 + #1 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #2 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #3 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #4 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #5 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #6 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #7 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + #8 0x41f6ed in _start (build-out/fuzz-unit-file+0x41f6ed) + +DEDUP_TOKEN: LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long)--fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) +0x602000005078 is located 38 bytes to the right of 2-byte region [0x602000005050,0x602000005052) +freed by thread T0 here: + #0 0x4a0882 in __interceptor_free /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:52:3 + #1 0x4ddfb7 in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:29:9 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: __interceptor_free--LLVMFuzzerTestOneInput--fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +previously allocated by thread T0 here: + #0 0x4a0b26 in malloc /src/llvm-project/compiler-rt/lib/asan/asan_malloc_linux.cpp:69:3 + #1 0x4ddfac in LLVMFuzzerTestOneInput /work/build/../../src/systemd/src/core/fuzz-unit-file.c:28:25 + #2 0x4fc653 in fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:611:15 + #3 0x4fbe3a in fuzzer::Fuzzer::RunOne(unsigned char const*, unsigned long, bool, fuzzer::InputInfo*, bool, bool*) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:514:3 + #4 0x4fdca4 in fuzzer::Fuzzer::ReadAndExecuteSeedCorpora(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:826:7 + #5 0x4fded9 in fuzzer::Fuzzer::Loop(std::__Fuzzer::vector >&) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerLoop.cpp:857:3 + #6 0x4ed53f in fuzzer::FuzzerDriver(int*, char***, int (*)(unsigned char const*, unsigned long)) /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerDriver.cpp:912:6 + #7 0x516b92 in main /src/llvm-project/compiler-rt/lib/fuzzer/FuzzerMain.cpp:20:10 + #8 0x7ff1b900c082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082) (BuildId: 1878e6b475720c7c51969e69ab2d276fae6d1dee) + +DEDUP_TOKEN: malloc--samLLVM2FuzzerTestOneInput --fuzzer::Fuzzer::ExecuteCallback(unsigned char const*, unsigned long) +SUMMARY: AddressSanitizer: heap-buffer-overflow /work/build/../../src/systemd/src/core/fuzz-unit-file.c:30:16 in samsamLLVM2FuzzerTestOneInput +Shadow bytes around the buggy address: + 0x0c047fff89b0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89c0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89d0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89e0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd + 0x0c047fff89f0: fa fa fd fd fa fa fd fd fa fa fd fd fa fa fd fd +=>0x0c047fff8a00: fa fa 00 02 fa fa 00 02 fa fa fd fa fa fa fa[fa] + 0x0c047fff8a10: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a20: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a30: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a40: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa + 0x0c047fff8a50: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa +Shadow byte legend (one shadow byte represents 8 application bytes): + Addressable: 00 + Partially addressable: 01 02 03 04 05 06 07 + Heap left redzone: fa + Freed heap region: fd + Stack left redzone: f1 + Stack mid redzone: f2 + Stack right redzone: f3 + Stack after return: f5 + Stack use after scope: f8 + Global redzone: f9 + Global init order: f6 + Poisoned by user: f7 + Container overflow: fc + Array cookie: ac + Intra object redzone: bb + ASan internal: fe + Left alloca redzone: ca + Right alloca redzone: cb +==78==ABORTING +MS: 0 ; base unit: 0000000000000000000000000000000000000000 +0x61,0x75,0x74,0x6f,0x6d,0x6f,0x75,0x6e,0x74,0x48, +automountH +artifact_prefix='/tmp/tmpjhswtxiw/'; Test unit written to /tmp/tmpjhswtxiw/crash-7be9e0f3a71d95f8d5e67c5a9d84273d6f4e3c03 +Base64: YXV0b21vdW50SA== +stat::number_of_executed_units: 314 +stat::average_exec_per_sec: 0 +stat::new_units_added: 0 +stat::slowest_unit_time_sec: 0 +stat::peak_rss_mb: 68 diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/.gitignore b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..30d9eff972346c4978622c6f567e7808ad21764d --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/.gitignore @@ -0,0 +1 @@ +wycheproof.zip \ No newline at end of file diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/generate_job.py b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/generate_job.py new file mode 100644 index 0000000000000000000000000000000000000000..508162e3110522d09ec4f671c7ac2c2e188e5ee7 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/generate_job.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Script for generating an OSS-Fuzz job for a wycheproof project.""" +import sys + + +def main(): + """Usage generate_job.py .""" + project = sys.argv[1] + print(f'Name: wycheproof_nosanitizer_{project}') + job_definition = f"""CUSTOM_BINARY = False +BAD_BUILD_CHECK = False +APP_NAME = WycheproofTarget.bash +THREAD_ALIVE_CHECK_INTERVAL = 10 +TEST_TIMEOUT = 3600 +CRASH_RETRIES = 1 +AGGREGATE_COVERAGE = False +TESTCASE_COVERAGE = False +FILE_GITHUB_ISSUE = False +MANAGED = False +MAX_FUZZ_THREADS = 1 +RELEASE_BUILD_BUCKET_PATH = gs://clusterfuzz-builds-wycheproof/{project}/{project}-none-([0-9]+).zip +PROJECT_NAME = {project} +SUMMARY_PREFIX = {project} +REVISION_VARS_URL = https://commondatastorage.googleapis.com/clusterfuzz-builds-wycheproof/{project}/{project}-none-%s.srcmap.json +FUZZ_LOGS_BUCKET = {project}-logs.clusterfuzz-external.appspot.com +CORPUS_BUCKET = {project}-corpus.clusterfuzz-external.appspot.com +QUARANTINE_BUCKET = {project}-quarantine.clusterfuzz-external.appspot.com +BACKUP_BUCKET = {project}-backup.clusterfuzz-external.appspot.com +AUTOMATIC_LABELS = Proj-{project},Engine-wycheproof +""" + print(job_definition) + + +if __name__ == '__main__': + main() diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/launcher.py b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca8435d12c20fd7f5f932cda0588ca10ff1070b --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/launcher.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Script for running wycheproof.""" + +import logging +import sys +import subprocess + + +def main(): + """Runs wycheproof.""" + if len(sys.argv) < 3: + logging.error('Usage: %s .', sys.argv[0]) + return 1 + + return subprocess.run(sys.argv[1:], check=False).returncode + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/package.bash b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/package.bash new file mode 100644 index 0000000000000000000000000000000000000000..842222587d1c414fba9451a9ac573f9cf35c93e1 --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/package.bash @@ -0,0 +1,18 @@ +#!/bin/bash +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +# Script for zipping ClusterFuzz's blackbox fuzzer for wycheproof. +zip wycheproof.zip run.py launcher.py diff --git a/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/run.py b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/run.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca11ef3e1a6c49744094776babbd0e029809c6f --- /dev/null +++ b/local-test-tika-delta-02/fuzz-tooling/infra/tools/wycheproof/run.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +# Copyright 2022 Google LLC +# +# 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. +# +################################################################################ +"""Script for creating "testcases" to run wycheproof on.""" + +import argparse +import os +import sys + + +def get_args(): + """Returns parsed program arguments.""" + parser = argparse.ArgumentParser() + parser.add_argument( + '--input_dir', + help='Ignored.', + ) + parser.add_argument('--output_dir', + help='Directory for writing testcases.', + required=True) + parser.add_argument('--no_of_files', type=int, help='Ignored.') + return parser.parse_args() + + +def main(): + """Generates a dummy testcase for use by a ClusterFuzz blackbox fuzzer.""" + args = get_args() + if not os.path.exists(args.output_dir): + os.mkdir(args.output_dir) + testcase = os.path.join(args.output_dir, 'fuzz-0') + with open(testcase, 'w') as file_handle: + file_handle.write(' ') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/README.md b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/README.md new file mode 100644 index 0000000000000000000000000000000000000000..13d35f16753d4bac1e2302602ba6e504f67e5378 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/README.md @@ -0,0 +1,16 @@ +# Zookeeper - Infinite Colon Problems + +This challenge is a very simple delta scan challenge. + +The challenge includes one synthetic vulnerability (vuln\_2) inside +improper iPv6 validation that leads to an infinite loop. + +The delta for this challenge contains the new iPv6 colon-counting functionality +in full, as well as a set of two unit tests to test the new functionality. + +## Challenge Rounds + +This challenge has been included in the following set of rounds. + +* Exhibition Round 1 +* Exhibition Round 2 diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/challenge.yaml b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/challenge.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4be5943e5e18ee7180485654b170cc2b74c1e5ad --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/challenge.yaml @@ -0,0 +1,32 @@ +metadata_spec_version: v1 + +name: 'Zookeeper - Infinite Colon Problems' + +# fuzz_tooling project info that pairs to this challenge +fuzz_tooling_project_name: 'zookeeper' +fuzz_tooling_url: "https://github.com/aixcc-finals/oss-fuzz-aixcc.git" +fuzz_tooling_ref: "challenge-state/zk-delta-01" + +challenge_type: delta # full | delta + +base_ref: f6f34f6d5b6d67205c34de617a0b99fe11e3d323 +delta_ref: challenges/zk-delta-01 + +# A list of the vulnerabilities included in this challenge +# This should always match the dir names in .aixcc/vulns/* +vulnerabilities: + - vuln_2 + +sarif: + broadcast: false + target: null + correct: null + +# harness fuzz targets available for this challenge +harnesses: + - 'DataTreeFuzzer' + - 'MessageTrackerPeekReceivedFuzzer' + - 'MultiProcessTxnFuzzer' + - 'ProcessTxnFuzzer' + - 'SerializeFuzzer' + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/delta.diff b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/delta.diff new file mode 100644 index 0000000000000000000000000000000000000000..7ceb5a8d3d405cdd0a47bd296f9d5647ca67a5b1 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/delta.diff @@ -0,0 +1,95 @@ +diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java +index a81a12baa..91952cad2 100644 +--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java ++++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java +@@ -105,7 +105,9 @@ private static void logMessages( + CircularBuffer messages, + Direction direction) { + String sentOrReceivedText = direction == Direction.SENT ? "sentBuffer to" : "receivedBuffer from"; +- ++ if (serverAddr.contains(":")) { ++ verifyIPv6(serverAddr); ++ } + if (messages.isEmpty()) { + LOG.info("No buffered timestamps for messages {} {}", sentOrReceivedText, serverAddr); + } else { +@@ -116,6 +118,34 @@ private static void logMessages( + } + } + ++ private static void verifyIPv6(String serverAddr) { ++ int maxColons = 8; ++ int cntColons = 0; ++ int i = serverAddr.indexOf(':'); ++ while (i > -1 && i < serverAddr.length() && cntColons < maxColons) { ++ cntColons++; ++ i = serverAddr.indexOf(':', i + 1); ++ } ++ //is there an extra? ++ int extraColons = countExtraColons(i, serverAddr); ++ //count extras ++ if (cntColons > 0 && (cntColons < maxColons || extraColons == 0)) { ++ return; ++ } ++ throw new IllegalArgumentException("bad ipv6: " + serverAddr + " too many colons=" + extraColons); ++ } ++ ++ private static int countExtraColons(int i, String serverAddr) { ++ if (i == -1) { ++ return 1; ++ } ++ int cnt = 1; ++ while (i > 0) { ++ cnt++; ++ i = serverAddr.indexOf(':'); ++ } ++ return cnt; ++ } + /** + * Direction for message track. + */ +diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java +index d400cf993..9e1d6b378 100644 +--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java ++++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java +@@ -20,6 +20,9 @@ + + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.junit.jupiter.api.Assertions.assertNull; ++import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.junit.jupiter.api.Assertions.assertTrue; ++ + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +@@ -127,4 +130,30 @@ public void testDumpToLog() { + assertNull(messageTracker.peekSent()); + assertNull(messageTracker.peekReceived()); + } ++ ++ @Test ++ public void testIPv6VerificationGood() { ++ MessageTracker messageTracker = new MessageTracker(10); ++ //see https://www.ibm.com/docs/en/ts4500-tape-library?topic=functionality-ipv4-ipv6-address-formats ++ for (String serverAddr : new String[] { ++ "2001:db8:3333:4444:5555:6666:7777:8888", ++ "2001:db8:3333:4444:CCCC:DDDD:EEEE:FFFF", ++ "::", "2001:db8::", "2001:db8::1234:5678", ++ "2001:0db8:0001:0000:0000:0ab9:C0A8:0102" ++ }) { ++ messageTracker.dumpToLog(serverAddr); ++ } ++ } ++ ++ @Test ++ public void testIPv6TooManyColons() { ++ final String serverAddr = "2001:db8:1234:0000:0000:0000:0000:0000:0000"; ++ MessageTracker messageTracker = new MessageTracker(10); ++ IllegalArgumentException thrown = assertThrows( ++ IllegalArgumentException.class, ++ () -> messageTracker.dumpToLog(serverAddr), ++ "Expected dumpToLog to throw IllegalArgumentException, but it didn't" ++ ); ++ assertTrue(thrown.getMessage().contains("too many colons=1")); ++ } + } diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/README.md b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/README.md new file mode 100644 index 0000000000000000000000000000000000000000..db00cbe84212be68c64671095b951db40a547515 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/README.md @@ -0,0 +1,13 @@ +# Zookeeper (vuln\_2) Infinite loop in ipv6 validation + +This is a vulnerability in a logging utility in MessageTracker.java +that attempts to check the validation of an iPv6 formatted string, +counting the number of colons and comparing them to a max value. + +The vulnerability itself is a failure to properly iterate over +values in the string. A simple infinite loop created by calling +String#indexOf without incrementing the last found index. + +Exploiting this vulnerability would allow someone to craft input +that causes a Denial-of-Service (DoS), reducing the availability +of the zookeeper service. diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/vuln.yaml b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/vuln.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d4284e0305fed66f138d50165b4c419ddc61bcb --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.aixcc/vulns/vuln_2/vuln.yaml @@ -0,0 +1,29 @@ +metadata_spec_version: v1 + +name: Infinite loop in ipv6 validation + +author: Tim Allison + +details: + + cwes: + - CWE-835 + - CWE-834 + + description: > + Infinite loop triggered by crafted ipv6 address. + + locations: + - path_from_root: 'zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java' + startLine: 121 + startColumn: 5 + endLine: 148 + endColumn: 6 + +pov: + blob: 'data.bin' + harness: 'MessageTrackerPeekReceivedFuzzer' + +patch: + good: 'good_patch.diff' + bad: 'bad_patch.diff' diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.asf.yaml b/local-test-zookeeper-delta-01/afc-zookeeper/.asf.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebadb92540fe85bb992f6841fb4ed9c91fe6d38b --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.asf.yaml @@ -0,0 +1,56 @@ +# +# 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. +# + +# https://cwiki.apache.org/confluence/display/INFRA/git+-+.asf.yaml+features + +github: + description: "Apache ZooKeeper" + homepage: https://zookeeper.apache.org + labels: + - java + - apache + - zookeeper + - consensus + - coordination + - zab + - database + - key-value + - distributed-database + - distributed-systems + - service-discovery + - configuration-management + - distributed-configuration + - hacktoberfest + features: + wiki: false + issues: false + projects: false + enabled_merge_buttons: + squash: true + merge: false + rebase: false + autolink_jira: + - ZOOKEEPER + +notifications: + jira_options: link label worklog + commits: commits@zookeeper.apache.org + issues: issues@zookeeper.apache.org + pullrequests: notifications@zookeeper.apache.org + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.gitattributes b/local-test-zookeeper-delta-01/afc-zookeeper/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..c3cc5e082bc88c26cc6b6823fd866699add502f7 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.gitattributes @@ -0,0 +1,21 @@ +# Auto detect text files and perform LF normalization +* text=auto + +*.cs text diff=csharp +*.java text diff=java +*.html text diff=html +*.py text diff=python +*.pl text diff=perl +*.pm text diff=perl +*.css text +*.js text +*.sql text + +*.sh text eol=lf + +*.bat text eol=crlf +*.cmd text eol=crlf +*.csproj text merge=union eol=crlf +*.sln text merge=union eol=crlf +*.vcxproj text merge=union eol=crlf +*.vcxproj.filters text merge=union eol=crlf diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/ci.yaml b/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/ci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0b212765f1b8d467e3f4f0b6a1b0e7ed3851d92 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/ci.yaml @@ -0,0 +1,106 @@ +# 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. + +# This workflow will build a Java project with Maven +# See also: +# https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: CI + +on: + push: + branches: [ '*' ] + pull_request: + branches: [ '*' ] + +jobs: + mvn: + strategy: + matrix: + profile: + - name: 'full-build-jdk8' + jdk: 8 + args: '-Pfull-build apache-rat:check verify -DskipTests spotbugs:check checkstyle:check' + - name: 'full-build-jdk11' + jdk: 11 + args: '-Pfull-build apache-rat:check verify -DskipTests spotbugs:check checkstyle:check' + - name: 'full-build-java-tests' + jdk: 11 + args: '-Pfull-build verify -Dsurefire-forkcount=1 -DskipCppUnit -Dsurefire.rerunFailingTestsCount=5' + - name: 'full-build-cppunit-tests' + jdk: 11 + args: '-Pfull-build verify -Dtest=_ -DfailIfNoTests=false' + fail-fast: false + timeout-minutes: 360 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK ${{ matrix.profile.jdk }} + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.profile.jdk }} + distribution: temurin + cache: 'maven' + - name: Show the first log message + run: git log -n1 + - name: Install C Dependencies + run: | + sudo apt update + sudo apt install -y libcppunit-dev libsasl2-dev + - name: Build with Maven (${{ matrix.profile.name }}) + run: mvn -B -V -e -ntp "-Dstyle.color=always" ${{ matrix.profile.args }} + env: + MAVEN_OPTS: -Djansi.force=true + - name: Upload unit test results + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: surefire-reports-${{ matrix.profile.name }} + path: ./**/target/surefire-reports/ + if-no-files-found: ignore + - name: Upload integration test results + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: failsafe-reports-${{ matrix.profile.name }} + path: ./**/target/failsafe-reports/ + if-no-files-found: ignore + - name: Upload cppunit test logs + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: cppunit-logs-${{ matrix.profile.name }} + path: ./zookeeper-client/zookeeper-client-c/target/c/TEST-*.txt + if-no-files-found: ignore + typo-check: + name: Typo Check + # only run on pull requests because of security reasons + # we shouldn't trust external actions for builds within the repository + if: ${{ github.event_name == 'pull_request' }} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Check typos + uses: crate-ci/typos@v1.22.4 + # To run the typo check locally, you can follow these steps: + # 1. Install typos locally using cargo: + # cargo install typos-cli + # 2. Run the typo check with the following command: + # typos + # FP is configured in the project root directory in the `.typos.toml` file. + # You can refer to the `.typos.toml` documentation here: + # https://github.com/crate-ci/typos/blob/master/docs/reference.md diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/manual.yaml b/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/manual.yaml new file mode 100644 index 0000000000000000000000000000000000000000..898fd283b9c15e33a8be932800f30949d3ce6be8 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.github/workflows/manual.yaml @@ -0,0 +1,78 @@ +# 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. + +# This workflow will build a Java project with Maven +# See also: +# https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# https://docs.github.com/en/actions/reference/events-that-trigger-workflows#manual-events + +name: Manual Build + +on: + workflow_dispatch: + inputs: + buildRef: + description: Ref to build (commit, branch, or refs/pull/1234/head or refs/pull/1234/merge) + required: true + default: refs/pull/1234/merge + mvnOpts: + description: Maven options + required: true + default: --fail-at-end + goals: + description: Maven goals + required: true + default: -Pfull-build apache-rat:check verify -DskipTests spotbugs:check checkstyle:check javadoc:jar +jobs: + mvn: + name: mvn (triggered by ${{ github.event.sender.login }}) + timeout-minutes: 360 + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.inputs.buildRef }} + - name: Set up JDK 11 + uses: actions/setup-java@v4 + with: + java-version: 11 + distribution: temurin + cache: 'maven' + - name: Show the first log message + run: git log -n1 + - name: Install C Dependencies + run: | + sudo apt update + sudo apt install -y libcppunit-dev libsasl2-dev + - name: Build with Maven + run: mvn -B -V -e -ntp "-Dstyle.color=always" ${{ github.event.inputs.mvnOpts }} ${{ github.event.inputs.goals }} + env: + MAVEN_OPTS: -Djansi.force=true + - name: Upload unit test results + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: surefire-reports + path: ./**/target/surefire-reports/ + if-no-files-found: ignore + - name: Upload integration test results + if: ${{ failure() }} + uses: actions/upload-artifact@v4 + with: + name: failsafe-reports + path: ./**/target/failsafe-reports/ + if-no-files-found: ignore diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/.typos.toml b/local-test-zookeeper-delta-01/afc-zookeeper/.typos.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3cd78c734f1a943160e048c812f03c7406a0238 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/.typos.toml @@ -0,0 +1,52 @@ +# +# 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. +# + +[default.extend-words] +# abbr +"aroun" = "aroun" +"delet" = "delet" +"dout" = "dout" +"fied" = "fied" +"fle" = "fle" +"fo" = "fo" +"hte" = "hte" +"nd" = "nd" +"nwe" = "nwe" +"pn" = "pn" +"strack" = "strack" +"thr" = "thr" +"ths" = "ths" +"wew" = "wew" +# keep for comptability +"pathes" = "pathes" +"shapshot" = "shapshot" +# keyword fp +"atend" = "atend" +"chec" = "chec" +"clos" = "clos" +"erro" = "erro" +"infor" = "infor" +"locahost" = "locahost" +"leafs" = "leafs" +"sceen" = "sceen" + +[files] +extend-exclude = [ + "zookeeper-server/src/test/java/org/apache/zookeeper/common/CertificatesToPlayWith.java", +] diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile new file mode 100644 index 0000000000000000000000000000000000000000..40fcdd5bbadd436160a65de8164ea1e3f9256ed4 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile @@ -0,0 +1,78 @@ +/* + * 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. + */ + +pipeline { + agent { + label 'Hadoop' + } + + options { + disableConcurrentBuilds() + buildDiscarder(logRotator(daysToKeepStr: '14')) + timeout(time: 2, unit: 'HOURS') + timestamps() + } + + triggers { + cron('@daily') + } + + stages { + stage('Prepare') { + matrix { + agent any + axes { + axis { + name 'JAVA_VERSION' + values 'jdk_1.8_latest', 'jdk_11_latest' + } + } + + tools { + maven "maven_latest" + jdk "${JAVA_VERSION}" + } + + stages { + stage('BuildAndTest') { + steps { + sh "git clean -fxd" + sh "mvn verify spotbugs:check checkstyle:check -Pfull-build -Dsurefire-forkcount=4" + } + post { + always { + junit '**/target/surefire-reports/TEST-*.xml' + archiveArtifacts '**/target/*.jar' + } + // Jenkins pipeline jobs fill slaves on PRs without this :( + cleanup() { + script { + sh label: 'Cleanup workspace', script: ''' + # See HADOOP-13951 + chmod -R u+rxw "${WORKSPACE}" + ''' + deleteDir() + } + } + } + } + } + } + } + } +} diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-PreCommit b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-PreCommit new file mode 100644 index 0000000000000000000000000000000000000000..8390e05b9295e82739443dac19aca705569abacd --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-PreCommit @@ -0,0 +1,62 @@ +/* + * 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. + */ + +pipeline { + agent { + label 'Hadoop' + } + + options { + disableConcurrentBuilds() + buildDiscarder(logRotator(daysToKeepStr: '14')) + timeout(time: 2, unit: 'HOURS') + timestamps() + } + + tools { + maven "maven_latest" + jdk "jdk_1.8_latest" + } + + stages { + stage('BuildAndTest') { + steps { + sh "git clean -fxd" + sh "mvn verify spotbugs:check checkstyle:check -Pfull-build -Dsurefire-forkcount=4" + } + post { + always { + junit '**/target/surefire-reports/TEST-*.xml' + } + } + } + } + + post { + // Jenkins pipeline jobs fill slaves on PRs without this :( + cleanup() { + script { + sh label: 'Cleanup workspace', script: ''' + # See HADOOP-13951 + chmod -R u+rxw "${WORKSPACE}" + ''' + deleteDir() + } + } + } +} diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-owasp b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-owasp new file mode 100644 index 0000000000000000000000000000000000000000..03ba497ac6d6a288be0fe3388e2e9a1618fbb8b9 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-owasp @@ -0,0 +1,61 @@ +/* + * 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. + */ + +pipeline { + agent { + label 'Hadoop' + } + + options { + buildDiscarder(logRotator(daysToKeepStr: '14')) + timeout(time: 2, unit: 'HOURS') + timestamps() + } + + tools { + maven "maven_latest" + jdk "jdk_1.8_latest" + } + + stages { + stage('BuildAndTest') { + steps { + sh "git clean -fxd" + sh "mvn clean package -DskipTests dependency-check:check" + } + post { + always { + archiveArtifacts '**/target/dependency-check-*' + } + } + } + } + + post { + // Jenkins pipeline jobs fill slaves on PRs without this :( + cleanup() { + script { + sh label: 'Cleanup workspace', script: ''' + # See HADOOP-13951 + chmod -R u+rxw "${WORKSPACE}" + ''' + deleteDir() + } + } + } +} diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-s390x b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-s390x new file mode 100644 index 0000000000000000000000000000000000000000..bd48a1c280a953914d30f55ab1ac5a17acb931e6 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/Jenkinsfile-s390x @@ -0,0 +1,73 @@ +/* + * 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. + */ + +pipeline { + agent { + label 's390x' + } + + options { + disableConcurrentBuilds() + buildDiscarder(logRotator(daysToKeepStr: '14')) + timeout(time: 2, unit: 'HOURS') + timestamps() + } + + triggers { + cron('@daily') + } + + stages { + stage('Prepare') { + + agent { + label 's390x' + } + + tools { + maven "maven_latest" + jdk "jdk_11_latest" + } + + stages { + stage('BuildAndTest') { + steps { + sh "git clean -fxd" + sh "mvn verify spotbugs:check checkstyle:check -Pfull-build -Dsurefire-forkcount=4" + } + post { + always { + junit '**/target/surefire-reports/TEST-*.xml' + archiveArtifacts '**/target/*.jar' + } + // Jenkins pipeline jobs fill slaves on PRs without this :( + cleanup() { + script { + sh label: 'Cleanup workspace', script: ''' + # See HADOOP-13951 + chmod -R u+rxw "${WORKSPACE}" + ''' + deleteDir() + } + } + } + } + } + } + } +} diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/LICENSE.txt b/local-test-zookeeper-delta-01/afc-zookeeper/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/LICENSE.txt @@ -0,0 +1,202 @@ + + 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. diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/NOTICE.txt b/local-test-zookeeper-delta-01/afc-zookeeper/NOTICE.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4e8d36bf5e6910cb40ecf250e83a98a0b2b463a --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/NOTICE.txt @@ -0,0 +1,35 @@ +Apache ZooKeeper +Copyright 2009-2024 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +This product includes software components originally +developed for Airlift (https://github.com/airlift/airlift), +licensed under the Apache 2.0 license. The licensing terms +for Airlift code can be found at: +https://github.com/airlift/airlift/blob/master/LICENSE + +This project also includes some files with the following licenses. + +These BSD licensed files: + ./zookeeper-client/zookeeper-client-c/src/hashtable/hashtable.c + ./zookeeper-client/zookeeper-client-c/src/hashtable/hashtable.h + ./zookeeper-client/zookeeper-client-c/src/hashtable/hashtable_itr.c + ./zookeeper-client/zookeeper-client-c/src/hashtable/hashtable_itr.h + ./zookeeper-client/zookeeper-client-c/src/hashtable/hashtable_private.h + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/yui-min.js + ./zookeeper-docs/src/main/resources/markdown/skin/prototype.js + +These MIT licensed files: + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/date.format.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/g.bar.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/g.dot.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/g.line.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/g.pie.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/g.raphael.js + ./zookeeper-contrib/zookeeper-contrib-loggraph/src/main/resources/webapp/org/apache/zookeeper/graph/resources/raphael.js + +This Apache 2.0 licensed file: +./zookeeper-contrib/zookeeper-contrib-zooinspector/src/main/java/com/nitido/utils/toaster/Toaster.java + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/README.md b/local-test-zookeeper-delta-01/afc-zookeeper/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cd9db2b460ca8da107893a30f07cea5fa65f4815 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/README.md @@ -0,0 +1,58 @@ +# Apache ZooKeeper [![GitHub Actions CI][ciBadge]][ciLink] [![Travis CI][trBadge]][trLink] [![Maven Central][mcBadge]][mcLink] [![License][liBadge]][liLink] + +

+ + https://zookeeper.apache.org/
+
+

+ +For the latest information about Apache ZooKeeper, please visit our website at: + + https://zookeeper.apache.org + +and our wiki, at: + + https://cwiki.apache.org/confluence/display/ZOOKEEPER + +## Packaging/release artifacts + +Either downloaded from https://zookeeper.apache.org/releases.html or +found in zookeeper-assembly/target directory after building the project with maven. + + apache-zookeeper-[version].tar.gz + + Contains all the source files which can be built by running: + mvn clean install + + To generate an aggregated apidocs for zookeeper-server and zookeeper-jute: + mvn javadoc:aggregate + (generated files will be at target/site/apidocs) + + apache-zookeeper-[version]-bin.tar.gz + + Contains all the jar files required to run ZooKeeper + Full documentation can also be found in the docs folder + +As of version 3.5.5, the parent, zookeeper and zookeeper-jute artifacts +are deployed to the central repository after the release +is voted on and approved by the Apache ZooKeeper PMC: + + https://repo1.maven.org/maven2/org/apache/zookeeper/zookeeper + +## Java 8 + +If you are going to compile with Java 1.8, you should use a +recent release at u211 or above. + +# Contributing +We always welcome new contributors to the project! See [How to Contribute](https://cwiki.apache.org/confluence/display/ZOOKEEPER/HowToContribute) for details on how to submit patches as pull requests and other aspects of our contribution workflow. + + +[ciBadge]: https://github.com/apache/zookeeper/workflows/CI/badge.svg +[ciLink]: https://github.com/apache/zookeeper/actions +[liBadge]: https://img.shields.io/github/license/apache/zookeeper?color=282661 +[liLink]: https://github.com/apache/zookeeper/blob/master/LICENSE.txt +[mcBadge]: https://img.shields.io/maven-central/v/org.apache.zookeeper/zookeeper +[mcLink]: https://zookeeper.apache.org/releases +[trBadge]: https://travis-ci.org/apache/zookeeper.svg?branch=master +[trLink]: https://travis-ci.org/apache/zookeeper diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/README_packaging.md b/local-test-zookeeper-delta-01/afc-zookeeper/README_packaging.md new file mode 100644 index 0000000000000000000000000000000000000000..0278aafcd906cc495fcd4692bdb59a9315f6ea78 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/README_packaging.md @@ -0,0 +1,80 @@ +# README file for Packaging Notes + +The ZooKeeper project publishes releases as tarballs. For ZooKeeper packages +specific to your OS (such as rpm and deb), consider using Apache Bigtop: + +http://bigtop.apache.org/ + + +## Requirements + +- you need maven to build the java code +- gcc, cppunit, openssl and python-setuptools are required to build C and python bindings (only needed when using `-Pfull-build`). Cyrus SASL is optional, but recommended for a maximally functional client. + +On RHEL machine: + +``` +yum install cppunit +yum install python-setuptools +yum install openssl openssl-devel +yum install cyrus-sasl-md5 cyrus-sasl-gssapi cyrus-sasl-devel +``` + +On Ubuntu (in case of 16.4+): + +``` +apt-get install libcppunit-dev +apt-get install python-setuptools python2.7-dev +apt-get install openssl libssl-dev +apt-get install libsasl2-modules-gssapi-mit libsasl2-modules libsasl2-dev +``` + + +## Package build command (using maven) + +Commands to clean everything and build the tarball package without executing the tests: `mvn clean install -DskipTests` + + +`zookeeper-assembly/target/apache-zookeeper--bin.tar.gz` tarball file structure layout: + +- `/bin` - User executables +- `/conf` - Configuration files +- `/lib` - ZooKeeper JAR files and all the required java library dependencies +- `/docs` - Documents + +Beside the binary tarball, you can find the whole original source project packaged into: +`zookeeper-assembly/target/apache-zookeeper-.tar.gz` + + +### Building the C client (using maven) + +To also build the C client, you need to activate the `full-build` profile: + +``` +mvn clean -Pfull-build +mvn install -Pfull-build -DskipTests +``` + +Optional parameters you might consider when using maven: +- `-Pfull-build` - activates the full-build profile, causing the C client to be built +- `-DskipTests` - this parameter will skip both java and C++ unit test execution during the build +- `-Pc-test-coverage` - activates the test coverage calculation during the execution of C client tests +- `-Dc-client-openssl` - specify ssl support and openssl library location. Default value: `yes`, resulting in + the autodetection of the openssl library. If the openssl library will not be detected, + then a warning will be shown and the C client will be compiled without SSL support. + Use `-Dc-client-openssl=no` to explicitly disable SSL feature in C client. Or use + `-Dc-client-openssl=/path/to/openssl/` if you want to use a non-default / specific + openssl library location. +- `-Dc-client-sasl` - specify SASL support and Cyrus SASL 1.x library location. Works similarly to the + `c-client-openssl` flag above (`yes`, `no`, or path). + +Please note: if you don't provide the `-Pfull-build` parameter, then the C client will not be built, the C client tests +will not be executed and the previous C client builds will no be cleaned up (e.g. with simply using `mvn clean`). + +The compiled C client can be found here: +- `zookeeper-client/zookeeper-client-c/target/c/bin` - User executable +- `zookeeper-client/zookeeper-client-c/target/c/lib` - Native libraries +- `zookeeper-client/zookeeper-client-c/target/c/include/zookeeper` - Native library headers + +The same folders gets archived to the `zookeeper-assembly/target/apache-zookeeper--lib.tar.gz` file, assuming +you activated the `full-build` maven profile. diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/README.txt b/local-test-zookeeper-delta-01/afc-zookeeper/bin/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..e70506dd71179a766b8bcec26f14d15761ba3578 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/README.txt @@ -0,0 +1,6 @@ +This directory contain scripts that allow easy access (classpath in particular) +to the ZooKeeper server and command line client. + +Files ending in .sh are unix and cygwin compatible + +Files ending in .cmd are msdos/windows compatible diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCleanup.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCleanup.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6fe0e758417abe9573877f2ffd4f12a90949d6c --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCleanup.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash + +# 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. + +# +# This script cleans up old transaction logs and snapshots +# + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +ZOODATADIR="$(grep "^[[:space:]]*dataDir=" "$ZOOCFG" | sed -e 's/.*=//')" +ZOODATALOGDIR="$(grep "^[[:space:]]*dataLogDir=" "$ZOOCFG" | sed -e 's/.*=//')" + +ZOO_LOG_FILE=zookeeper-$USER-cleanup-$HOSTNAME.log + +if [ "x$ZOODATALOGDIR" = "x" ] +then +"$JAVA" "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.PurgeTxnLog "$ZOODATADIR" $* +else +"$JAVA" "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.PurgeTxnLog "$ZOODATALOGDIR" "$ZOODATADIR" $* +fi diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.cmd new file mode 100644 index 0000000000000000000000000000000000000000..d20cdaaf45163aba7647b915d85e55d6099c345e --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.cmd @@ -0,0 +1,26 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOO_LOG_FILE=zookeeper-%USERNAME%-cli-%COMPUTERNAME%.log + +set ZOOMAIN=org.apache.zookeeper.ZooKeeperMain +call %JAVA% "-Dzookeeper.log.dir=%ZOO_LOG_DIR%" "-Dzookeeper.log.file=%ZOO_LOG_FILE%" -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.sh new file mode 100644 index 0000000000000000000000000000000000000000..3810e7f6880c5aad2c244fa9a23c0e6697df7a39 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkCli.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash + +# 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. + +# +# This script cleans up old transaction logs and snapshots +# + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +ZOO_LOG_FILE=zookeeper-$USER-cli-$HOSTNAME.log + +"$JAVA" "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -cp "$CLASSPATH" $CLIENT_JVMFLAGS $JVMFLAGS \ + org.apache.zookeeper.ZooKeeperMain "$@" diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.cmd new file mode 100644 index 0000000000000000000000000000000000000000..5a01af6623b582413c9ac8795ace1386d79198cc --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.cmd @@ -0,0 +1,53 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +set ZOOCFGDIR=%~dp0%..\conf +set ZOO_LOG_DIR=%~dp0%..\logs + +REM for sanity sake assume Java 1.6 +REM see: http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html + +REM add the zoocfg dir to classpath +set CLASSPATH=%ZOOCFGDIR% + +REM make it work in the release +SET CLASSPATH=%~dp0..\*;%~dp0..\lib\*;%CLASSPATH% + +REM make it work for developers +SET CLASSPATH=%~dp0..\build\classes;%~dp0..\build\lib\*;%CLASSPATH% + +set ZOOCFG=%ZOOCFGDIR%\zoo.cfg + +@REM setup java environment variables + +if not defined JAVA_HOME ( + echo Error: JAVA_HOME is not set. + goto :eof +) + +set JAVA_HOME=%JAVA_HOME:"=% + +if not exist "%JAVA_HOME%"\bin\java.exe ( + echo Error: JAVA_HOME is incorrectly set: %JAVA_HOME% + echo Expected to find java.exe here: %JAVA_HOME%\bin\java.exe + goto :eof +) + +REM strip off trailing \ from JAVA_HOME or java does not start +if "%JAVA_HOME:~-1%" EQU "\" set "JAVA_HOME=%JAVA_HOME:~0,-1%" + +set JAVA="%JAVA_HOME%"\bin\java + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.sh new file mode 100644 index 0000000000000000000000000000000000000000..46a4621c42bfa854fc4f6c4e5221fa7d05a52fee --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkEnv.sh @@ -0,0 +1,153 @@ +#!/usr/bin/env bash + +# 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. + +# This script should be sourced into other zookeeper +# scripts to setup the env variables + +# We use ZOOCFGDIR if defined, +# otherwise we use /etc/zookeeper +# or the conf directory that is +# a sibling of this script's directory. +# Or you can specify the ZOOCFGDIR using the +# '--config' option in the command line. + +ZOOBINDIR="${ZOOBINDIR:-/usr/bin}" +ZOOKEEPER_PREFIX="${ZOOBINDIR}/.." + +#check to see if the conf dir is given as an optional argument +if [ $# -gt 1 ] +then + if [ "--config" = "$1" ] + then + shift + confdir=$1 + shift + ZOOCFGDIR=$confdir + fi +fi + +if [ "x$ZOOCFGDIR" = "x" ] +then + if [ -e "${ZOOKEEPER_PREFIX}/conf" ]; then + ZOOCFGDIR="$ZOOBINDIR/../conf" + else + ZOOCFGDIR="$ZOOBINDIR/../etc/zookeeper" + fi +fi + +if [ -f "${ZOOCFGDIR}/zookeeper-env.sh" ]; then + . "${ZOOCFGDIR}/zookeeper-env.sh" +fi + +if [ "x$ZOOCFG" = "x" ] +then + ZOOCFG="zoo.cfg" +fi + +ZOOCFG="$ZOOCFGDIR/$ZOOCFG" + +if [ -f "$ZOOCFGDIR/java.env" ] +then + . "$ZOOCFGDIR/java.env" +fi + +if [ "x${ZOO_LOG_DIR}" = "x" ] +then + ZOO_LOG_DIR="$ZOOKEEPER_PREFIX/logs" +fi + +if [[ -n "$JAVA_HOME" ]] && [[ -x "$JAVA_HOME/bin/java" ]]; then + JAVA="$JAVA_HOME/bin/java" +elif type -p java; then + JAVA=java +else + echo "Error: JAVA_HOME is not set and java could not be found in PATH." 1>&2 + exit 1 +fi + +#add the zoocfg dir to classpath +CLASSPATH="$ZOOCFGDIR:$CLASSPATH" + +for i in "$ZOOBINDIR"/../zookeeper-server/src/main/resources/lib/*.jar +do + CLASSPATH="$i:$CLASSPATH" +done + +#make it work in the binary package +#(use array for LIBPATH to account for spaces within wildcard expansion) +if ls "${ZOOKEEPER_PREFIX}"/share/zookeeper/zookeeper-*.jar > /dev/null 2>&1; then + LIBPATH=("${ZOOKEEPER_PREFIX}"/share/zookeeper/*.jar) +else + #release tarball format + for i in "$ZOOBINDIR"/../zookeeper-*.jar + do + CLASSPATH="$i:$CLASSPATH" + done + LIBPATH=("${ZOOBINDIR}"/../lib/*.jar) +fi + +for i in "${LIBPATH[@]}" +do + CLASSPATH="$i:$CLASSPATH" +done + +#make it work for developers +for d in "$ZOOBINDIR"/../build/lib/*.jar +do + CLASSPATH="$d:$CLASSPATH" +done + +#make it work for developers +for d in "$ZOOBINDIR"/../zookeeper-server/target/lib/*.jar +do + CLASSPATH="$d:$CLASSPATH" +done + +#make it work for developers +for d in "$ZOOBINDIR"/../zookeeper-metrics-providers/zookeeper-prometheus-metrics/target/lib/*.jar +do + CLASSPATH="$d:$CLASSPATH" +done + +#make it work for developers +CLASSPATH="$ZOOBINDIR/../build/classes:$CLASSPATH" + +#make it work for developers +CLASSPATH="$ZOOBINDIR/../zookeeper-server/target/classes:$CLASSPATH" + +#make it work for developers +CLASSPATH="$ZOOBINDIR/../zookeeper-metrics-providers/zookeeper-prometheus-metrics/target/classes:$CLASSPATH" + +case "`uname`" in + CYGWIN*|MINGW*) cygwin=true ;; + *) cygwin=false ;; +esac + +if $cygwin +then + CLASSPATH=`cygpath -wp "$CLASSPATH"` +fi + +#echo "CLASSPATH=$CLASSPATH" + +# default heap for zookeeper server +ZK_SERVER_HEAP="${ZK_SERVER_HEAP:-1000}" +export SERVER_JVMFLAGS="-Xmx${ZK_SERVER_HEAP}m $SERVER_JVMFLAGS" + +# default heap for zookeeper client +ZK_CLIENT_HEAP="${ZK_CLIENT_HEAP:-256}" +export CLIENT_JVMFLAGS="-Xmx${ZK_CLIENT_HEAP}m $CLIENT_JVMFLAGS" diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer-initialize.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer-initialize.sh new file mode 100644 index 0000000000000000000000000000000000000000..062e265915c0971cca947ceeb17d0dee0f895f8f --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer-initialize.sh @@ -0,0 +1,141 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +usage() { + # the configfile will be properly formatted as long as the + # configfile path is less then 40 chars, otw the line will look a + # bit weird, but otherwise it's fine + printf "usage: $0 + Optional parameters: + -h Display this message + --help Display this message + --configfile=%-40s ZooKeeper config file + --myid=# Set the myid to be used, if any (1-255) + --force Force creation of the data/txnlog dirs +" "$ZOOCFG" + exit 1 +} + +if [ $? != 0 ] ; then + usage + exit 1 +fi + +initialize() { + if [ ! -e "$ZOOCFG" ]; then + echo "Unable to find config file at $ZOOCFG" + exit 1 + fi + + ZOO_DATADIR="$(grep "^[[:space:]]*dataDir" "$ZOOCFG" | sed -e 's/.*=//')" + ZOO_DATALOGDIR="$(grep "^[[:space:]]*dataLogDir" "$ZOOCFG" | sed -e 's/.*=//')" + + if [ -z "$ZOO_DATADIR" ]; then + echo "Unable to determine dataDir from $ZOOCFG" + exit 1 + fi + + if [ $FORCE ]; then + echo "Force enabled, data/txnlog directories will be re-initialized" + else + # we create if version-2 exists (ie real data), not the + # parent. See comments in following section for more insight + if [ -d "$ZOO_DATADIR/version-2" ]; then + echo "ZooKeeper data directory already exists at $ZOO_DATADIR (or use --force to force re-initialization)" + exit 1 + fi + + if [ -n "$ZOO_DATALOGDIR" ] && [ -d "$ZOO_DATALOGDIR/version-2" ]; then + echo "ZooKeeper txnlog directory already exists at $ZOO_DATALOGDIR (or use --force to force re-initialization)" + exit 1 + fi + fi + + # remove the child files that we're (not) interested in, not the + # parent. this allows for parent to be installed separately, and + # permissions to be set based on overarching requirements. by + # default we'll use the permissions of the user running this + # script for the files contained by the parent. note also by using + # -p the parent(s) will be created if it doesn't already exist + rm -rf "$ZOO_DATADIR/myid" 2>/dev/null >/dev/null + rm -rf "$ZOO_DATADIR/version-2" 2>/dev/null >/dev/null + mkdir -p "$ZOO_DATADIR/version-2" + + if [ -n "$ZOO_DATALOGDIR" ]; then + rm -rf "$ZOO_DATALOGDIR/myid" 2>/dev/null >/dev/null + rm -rf "$ZOO_DATALOGDIR/version-2" 2>/dev/null >/dev/null + mkdir -p "$ZOO_DATALOGDIR/version-2" + fi + + if [ $MYID ]; then + echo "Using myid of $MYID" + echo $MYID > "$ZOO_DATADIR/myid" + else + echo "No myid provided, be sure to specify it in $ZOO_DATADIR/myid if using non-standalone" + fi + + touch "$ZOO_DATADIR/initialize" +} + +while [ ! -z "$1" ]; do + case "$1" in + --configfile) + ZOOCFG=$2; shift 2 + ;; + --configfile=?*) + ZOOCFG=${1#*=}; shift 1 + ;; + --myid) + MYID=$2; shift 2 + ;; + --myid=?*) + MYID=${1#*=}; shift 1 + ;; + --force) + FORCE=1; shift 1 + ;; + -h) + usage + ;; + --help) + usage + ;; + *) + echo "Unknown option: $1" + usage + exit 1 + ;; + esac +done +initialize diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.cmd new file mode 100644 index 0000000000000000000000000000000000000000..f58ea36fc728849268db4afeab6f94828c984cab --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.cmd @@ -0,0 +1,26 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.quorum.QuorumPeerMain +set ZOO_LOG_FILE=zookeeper-%USERNAME%-server-%COMPUTERNAME%.log + +echo on +call %JAVA% "-Dzookeeper.log.dir=%ZOO_LOG_DIR%" "-Dzookeeper.log.file=%ZOO_LOG_FILE%" "-XX:+HeapDumpOnOutOfMemoryError" "-XX:OnOutOfMemoryError=cmd /c taskkill /pid %%%%p /t /f" -cp "%CLASSPATH%" %ZOOMAIN% "%ZOOCFG%" %* + +endlocal diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.sh new file mode 100644 index 0000000000000000000000000000000000000000..91d335c00ad5bd334bfb22ccbe99df12a3afaafd --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkServer.sh @@ -0,0 +1,320 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +# See the following page for extensive details on setting +# up the JVM to accept JMX remote management: +# http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html +# by default we allow local JMX connections +if [ "x$JMXLOCALONLY" = "x" ] +then + JMXLOCALONLY=false +fi + +if [ "x$JMXDISABLE" = "x" ] || [ "$JMXDISABLE" = 'false' ] +then + echo "ZooKeeper JMX enabled by default" >&2 + if [ "x$JMXPORT" = "x" ] + then + # for some reason these two options are necessary on jdk6 on Ubuntu + # accord to the docs they are not necessary, but otw jconsole cannot + # do a local attach + ZOOMAIN="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=$JMXLOCALONLY org.apache.zookeeper.server.quorum.QuorumPeerMain" + else + if [ "x$JMXAUTH" = "x" ] + then + JMXAUTH=false + fi + if [ "x$JMXSSL" = "x" ] + then + JMXSSL=false + fi + if [ "x$JMXLOG4J" = "x" ] + then + JMXLOG4J=true + fi + echo "ZooKeeper remote JMX Port set to $JMXPORT" >&2 + echo "ZooKeeper remote JMX authenticate set to $JMXAUTH" >&2 + echo "ZooKeeper remote JMX ssl set to $JMXSSL" >&2 + echo "ZooKeeper remote JMX log4j set to $JMXLOG4J" >&2 + if [ "x$JMXHOSTNAME" = "x" ] + then + ZOOMAIN="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=$JMXPORT -Dcom.sun.management.jmxremote.authenticate=$JMXAUTH -Dcom.sun.management.jmxremote.ssl=$JMXSSL -Dzookeeper.jmx.log4j.disable=$JMXLOG4J org.apache.zookeeper.server.quorum.QuorumPeerMain" + else + echo "ZooKeeper remote JMX Hostname set to $JMXHOSTNAME" >&2 + ZOOMAIN="-Dcom.sun.management.jmxremote -Djava.rmi.server.hostname=$JMXHOSTNAME -Dcom.sun.management.jmxremote.port=$JMXPORT -Dcom.sun.management.jmxremote.authenticate=$JMXAUTH -Dcom.sun.management.jmxremote.ssl=$JMXSSL -Dzookeeper.jmx.log4j.disable=$JMXLOG4J org.apache.zookeeper.server.quorum.QuorumPeerMain" + fi + fi +else + echo "JMX disabled by user request" >&2 + ZOOMAIN="org.apache.zookeeper.server.quorum.QuorumPeerMain" +fi + +if [ "x$SERVER_JVMFLAGS" != "x" ] +then + JVMFLAGS="$SERVER_JVMFLAGS $JVMFLAGS" +fi + +if [ "x$2" != "x" ] +then + ZOOCFG="$ZOOCFGDIR/$2" +fi + +# if we give a more complicated path to the config, don't screw around in $ZOOCFGDIR +if [ "x$(dirname "$ZOOCFG")" != "x$ZOOCFGDIR" ] +then + ZOOCFG="$2" +fi + +if $cygwin +then + ZOOCFG=`cygpath -wp "$ZOOCFG"` + # cygwin has a "kill" in the shell itself, gets confused + KILL=/bin/kill +else + KILL=kill +fi + +echo "Using config: $ZOOCFG" >&2 + +case "$OSTYPE" in +*solaris*) + GREP=/usr/xpg4/bin/grep + ;; +*) + GREP=grep + ;; +esac +ZOO_DATADIR="$($GREP "^[[:space:]]*dataDir" "$ZOOCFG" | sed -e 's/.*=//')" +ZOO_DATADIR="$(echo -e "${ZOO_DATADIR}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')" +ZOO_DATALOGDIR="$($GREP "^[[:space:]]*dataLogDir" "$ZOOCFG" | sed -e 's/.*=//')" + +# iff autocreate is turned off and the datadirs don't exist fail +# immediately as we can't create the PID file, etc..., anyway. +if [ -n "$ZOO_DATADIR_AUTOCREATE_DISABLE" ]; then + if [ ! -d "$ZOO_DATADIR/version-2" ]; then + echo "ZooKeeper data directory is missing at $ZOO_DATADIR fix the path or run initialize" + exit 1 + fi + + if [ -n "$ZOO_DATALOGDIR" ] && [ ! -d "$ZOO_DATALOGDIR/version-2" ]; then + echo "ZooKeeper txnlog directory is missing at $ZOO_DATALOGDIR fix the path or run initialize" + exit 1 + fi + ZOO_DATADIR_AUTOCREATE="-Dzookeeper.datadir.autocreate=false" +fi + +if [ -z "$ZOOPIDFILE" ]; then + if [ ! -d "$ZOO_DATADIR" ]; then + mkdir -p "$ZOO_DATADIR" + fi + ZOOPIDFILE="$ZOO_DATADIR/zookeeper_server.pid" +else + # ensure it exists, otw stop will fail + mkdir -p "$(dirname "$ZOOPIDFILE")" +fi + +if [ ! -w "$ZOO_LOG_DIR" ] ; then +mkdir -p "$ZOO_LOG_DIR" +fi + +ZOO_LOG_FILE=${ZOO_LOG_FILE:-zookeeper-$USER-server-$HOSTNAME.log} +_ZOO_DAEMON_OUT="$ZOO_LOG_DIR/zookeeper-$USER-server-$HOSTNAME.out" + +case $1 in +start) + echo -n "Starting zookeeper ... " + if [ -f "$ZOOPIDFILE" ]; then + if kill -0 `cat "$ZOOPIDFILE"` > /dev/null 2>&1; then + echo $command already running as process `cat "$ZOOPIDFILE"`. + exit 1 + fi + fi + nohup "$JAVA" $ZOO_DATADIR_AUTOCREATE "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" \ + "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError='kill -9 %p' \ + -cp "$CLASSPATH" $JVMFLAGS $ZOOMAIN "$ZOOCFG" > "$_ZOO_DAEMON_OUT" 2>&1 < /dev/null & + if [ $? -eq 0 ] + then + case "$OSTYPE" in + *solaris*) + /bin/echo "${!}\\c" > "$ZOOPIDFILE" + ;; + aix*) + /bin/echo "$!\c" > "$ZOOPIDFILE" + ;; + *) + /bin/echo -n $! > "$ZOOPIDFILE" + ;; + esac + if [ $? -eq 0 ]; + then + sleep 1 + pid=$(cat "${ZOOPIDFILE}") + if ps -p "${pid}" > /dev/null 2>&1; then + echo STARTED + else + echo FAILED TO START + exit 1 + fi + else + echo FAILED TO WRITE PID + exit 1 + fi + else + echo SERVER DID NOT START + exit 1 + fi + ;; +start-foreground) + ZOO_CMD=(exec "$JAVA") + if [ "${ZOO_NOEXEC}" != "" ]; then + ZOO_CMD=("$JAVA") + fi + "${ZOO_CMD[@]}" $ZOO_DATADIR_AUTOCREATE "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" \ + "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError='kill -9 %p' \ + -cp "$CLASSPATH" $JVMFLAGS $ZOOMAIN "$ZOOCFG" + ;; +print-cmd) + echo "\"$JAVA\" $ZOO_DATADIR_AUTOCREATE -Dzookeeper.log.dir=\"${ZOO_LOG_DIR}\" \ + -Dzookeeper.log.file=\"${ZOO_LOG_FILE}\" \ + -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError='kill -9 %p' \ + -cp \"$CLASSPATH\" $JVMFLAGS $ZOOMAIN \"$ZOOCFG\" > \"$_ZOO_DAEMON_OUT\" 2>&1 < /dev/null" + ;; +stop) + echo -n "Stopping zookeeper ... " + if [ ! -f "$ZOOPIDFILE" ] + then + echo "no zookeeper to stop (could not find file $ZOOPIDFILE)" + else + $KILL $(cat "$ZOOPIDFILE") + rm "$ZOOPIDFILE" + sleep 1 + echo STOPPED + fi + exit 0 + ;; +version) + ZOOMAIN=org.apache.zookeeper.version.VersionInfoMain + $JAVA -cp "$CLASSPATH" $ZOOMAIN 2> /dev/null + ;; +restart) + shift + "$0" stop ${@} + sleep 3 + "$0" start ${@} + ;; +status) + # -q is necessary on some versions of linux where nc returns too quickly, and no stat result is output + isSSL="false" + clientPortAddress=`$GREP "^[[:space:]]*clientPortAddress[^[:alpha:]]" "$ZOOCFG" | sed -e 's/.*=//'` + if ! [ $clientPortAddress ] + then + clientPortAddress="localhost" + fi + clientPort=`$GREP "^[[:space:]]*clientPort[^[:alpha:]]" "$ZOOCFG" | sed -e 's/.*=//'` + if ! [[ "$clientPort" =~ ^[0-9]+$ ]] + then + dataDir=`$GREP "^[[:space:]]*dataDir" "$ZOOCFG" | sed -e 's/.*=//'` + myid=`cat "$dataDir/myid" 2> /dev/null` + if ! [[ "$myid" =~ ^[0-9]+$ ]] ; then + echo "myid could not be determined, will not able to locate clientPort in the server configs." + else + clientPortAndAddress=`$GREP "^[[:space:]]*server.$myid=.*;.*" "$ZOOCFG" | sed -e 's/.*=//' | sed -e 's/.*;//'` + if [ ! "$clientPortAndAddress" ] ; then + echo "Client port not found in static config file. Looking in dynamic config file." + dynamicConfigFile=`$GREP "^[[:space:]]*dynamicConfigFile" "$ZOOCFG" | sed -e 's/.*=//'` + clientPortAndAddress=`$GREP "^[[:space:]]*server.$myid=.*;.*" "$dynamicConfigFile" | sed -e 's/.*=//' | sed -e 's/.*;//'` + fi + if [ ! "$clientPortAndAddress" ] ; then + echo "Client port not found in the server configs" + else + if [[ "$clientPortAndAddress" =~ ^.*:[0-9]+ ]] ; then + if [[ "$clientPortAndAddress" =~ \[.*\]:[0-9]+ ]] ; then + # Extracts address from address:port for example extracts 127::1 from "[127::1]:2181" + clientPortAddress=`echo "$clientPortAndAddress" | sed -e 's|\[||' | sed -e 's|\]:.*||'` + else + clientPortAddress=`echo "$clientPortAndAddress" | sed -e 's/:.*//'` + fi + fi + clientPort=`echo "$clientPortAndAddress" | sed -e 's/.*://'` + fi + fi + fi + if [ ! "$clientPort" ] ; then + echo "Client port not found. Looking for secureClientPort in the static config." + secureClientPort=`$GREP "^[[:space:]]*secureClientPort[^[:alpha:]]" "$ZOOCFG" | sed -e 's/.*=//'` + if [ "$secureClientPort" ] ; then + isSSL="true" + clientPort=$secureClientPort + clientPortAddress=`$GREP "^[[:space:]]*secureClientPortAddress[^[:alpha:]]" "$ZOOCFG" | sed -e 's/.*=//'` + if ! [ $clientPortAddress ] + then + clientPortAddress="localhost" + fi + else + echo "Unable to find either secure or unsecure client port in any configs. Terminating." + exit 1 + fi + fi + echo "Client port found: $clientPort. Client address: $clientPortAddress. Client SSL: $isSSL." + STAT=`"$JAVA" "-Dzookeeper.log.dir=${ZOO_LOG_DIR}" "-Dzookeeper.log.file=${ZOO_LOG_FILE}" \ + -cp "$CLASSPATH" $CLIENT_JVMFLAGS $JVMFLAGS org.apache.zookeeper.client.FourLetterWordMain \ + $clientPortAddress $clientPort srvr $isSSL 2> /dev/null \ + | $GREP Mode` + if [ "x$STAT" = "x" ] + then + if [ "$isSSL" = "true" ] ; then + echo " " + echo "Note: We used secureClientPort ($secureClientPort) to establish connection, but we failed. The 'status'" + echo " command establishes a client connection to the server to execute diagnostic commands. Please make sure you" + echo " provided all the Client SSL connection related parameters in the CLIENT_JVMFLAGS environment variable! E.g.:" + echo " CLIENT_JVMFLAGS=\"-Dzookeeper.clientCnxnSocket=org.apache.zookeeper.ClientCnxnSocketNetty" + echo " -Dzookeeper.ssl.trustStore.location=/tmp/clienttrust.jks -Dzookeeper.ssl.trustStore.password=password" + echo " -Dzookeeper.ssl.keyStore.location=/tmp/client.jks -Dzookeeper.ssl.keyStore.password=password" + echo " -Dzookeeper.client.secure=true\" ./zkServer.sh status" + echo " " + fi + echo "Error contacting service. It is probably not running." + exit 1 + else + echo $STAT + exit 0 + fi + ;; +*) + echo "Usage: $0 [--config ] {start|start-foreground|stop|version|restart|status|print-cmd}" >&2 + +esac diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.cmd new file mode 100644 index 0000000000000000000000000000000000000000..66c2db7cc11489adb82426bf9b23da86441f98f6 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.cmd @@ -0,0 +1,24 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.SnapshotFormatter +call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.sh new file mode 100644 index 0000000000000000000000000000000000000000..1664d596f3771585cbcc1d2308ac5a774dc3e3cc --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapShotToolkit.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +"$JAVA" -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.SnapshotFormatter "$@" + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.cmd new file mode 100644 index 0000000000000000000000000000000000000000..84a3c45cd12c90aa8f820afd738b550adae40da7 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.cmd @@ -0,0 +1,24 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.SnapshotComparer +call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.sh new file mode 100644 index 0000000000000000000000000000000000000000..b284c902d39ee65a71c2129c6d0a592960661c63 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotComparer.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +"$JAVA" -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.SnapshotComparer "$@" diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.cmd new file mode 100644 index 0000000000000000000000000000000000000000..a5fb783edaa77965914180f0ec4d9d44ab46c26b --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.cmd @@ -0,0 +1,24 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.SnapshotRecursiveSummary +call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.sh new file mode 100644 index 0000000000000000000000000000000000000000..888fdc01138b225b13cd8bc9e5e11ea1aacb7eee --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkSnapshotRecursiveSummaryToolkit.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + # shellcheck source=/bin/zkEnv.sh + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +"$JAVA" -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.SnapshotRecursiveSummary "$@" + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.cmd b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.cmd new file mode 100644 index 0000000000000000000000000000000000000000..8fd9d5312f47419994ce7ea16407466eb40373ff --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.cmd @@ -0,0 +1,24 @@ +@echo off +REM Licensed to the Apache Software Foundation (ASF) under one or more +REM contributor license agreements. See the NOTICE file distributed with +REM this work for additional information regarding copyright ownership. +REM The ASF licenses this file to You under the Apache License, Version 2.0 +REM (the "License"); you may not use this file except in compliance with +REM the License. You may obtain a copy of the License at +REM +REM http://www.apache.org/licenses/LICENSE-2.0 +REM +REM Unless required by applicable law or agreed to in writing, software +REM distributed under the License is distributed on an "AS IS" BASIS, +REM WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +REM See the License for the specific language governing permissions and +REM limitations under the License. + +setlocal +call "%~dp0zkEnv.cmd" + +set ZOOMAIN=org.apache.zookeeper.server.persistence.TxnLogToolkit +call %JAVA% -cp "%CLASSPATH%" %ZOOMAIN% %* + +endlocal + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.sh b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.sh new file mode 100644 index 0000000000000000000000000000000000000000..8beed20ddd71eea3e50a3196a72a2b438f7eab9f --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/bin/zkTxnLogToolkit.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +# 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. + +# +# If this scripted is run out of /usr/bin or some other system bin directory +# it should be linked to and not copied. Things like java jar files are found +# relative to the canonical path of this script. +# + +# use POSIX interface, symlink is followed automatically +ZOOBIN="${BASH_SOURCE-$0}" +ZOOBIN="$(dirname "${ZOOBIN}")" +ZOOBINDIR="$(cd "${ZOOBIN}"; pwd)" + +if [ -e "$ZOOBIN/../libexec/zkEnv.sh" ]; then + . "$ZOOBINDIR"/../libexec/zkEnv.sh +else + . "$ZOOBINDIR"/zkEnv.sh +fi + +"$JAVA" -cp "$CLASSPATH" $JVMFLAGS \ + org.apache.zookeeper.server.persistence.TxnLogToolkit "$@" + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-simple.xml b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-simple.xml new file mode 100644 index 0000000000000000000000000000000000000000..004cd68e417c137033e29e7857b7ee23f6312d0d --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-simple.xml @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-strict.xml b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-strict.xml new file mode 100644 index 0000000000000000000000000000000000000000..4f2d55b103fe36bd1fd1d509494dd6823646b02c --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyle-strict.xml @@ -0,0 +1,432 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/checkstyleSuppressions.xml b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyleSuppressions.xml new file mode 100644 index 0000000000000000000000000000000000000000..513de6b4d80eadadb9e0239ae1a133df2a540d33 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/checkstyleSuppressions.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/conf/configuration.xsl b/local-test-zookeeper-delta-01/afc-zookeeper/conf/configuration.xsl new file mode 100644 index 0000000000000000000000000000000000000000..377cdbeb937fd5a0532db30997ccc4bd80a7c38e --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/conf/configuration.xsl @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + +
namevaluedescription
+ + +
+
diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/conf/logback.xml b/local-test-zookeeper-delta-01/afc-zookeeper/conf/logback.xml new file mode 100644 index 0000000000000000000000000000000000000000..84a5389695478906b3902ec57390a0c15f081b65 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/conf/logback.xml @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + %d{ISO8601} [myid:%X{myid}] - %-5p [%t:%C{1}@%L] - %m%n + + + ${zookeeper.console.threshold} + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/conf/zoo_sample.cfg b/local-test-zookeeper-delta-01/afc-zookeeper/conf/zoo_sample.cfg new file mode 100644 index 0000000000000000000000000000000000000000..d0db6e99a1dca1d72a9ad1c928ff8a46800e9052 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/conf/zoo_sample.cfg @@ -0,0 +1,37 @@ +# The number of milliseconds of each tick +tickTime=2000 +# The number of ticks that the initial +# synchronization phase can take +initLimit=10 +# The number of ticks that can pass between +# sending a request and getting an acknowledgement +syncLimit=5 +# the directory where the snapshot is stored. +# do not use /tmp for storage, /tmp here is just +# example sakes. +dataDir=/tmp/zookeeper +# the port at which the clients will connect +clientPort=2181 +# the maximum number of client connections. +# increase this if you need to handle more clients +#maxClientCnxns=60 +# +# Be sure to read the maintenance section of the +# administrator guide before turning on autopurge. +# +# https://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance +# +# The number of snapshots to retain in dataDir +#autopurge.snapRetainCount=3 +# Purge task interval in hours +# Set to "0" to disable auto purge feature +#autopurge.purgeInterval=1 + +## Metrics Providers +# +# https://prometheus.io Metrics Exporter +#metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider +#metricsProvider.httpHost=0.0.0.0 +#metricsProvider.httpPort=7000 +#metricsProvider.exportJvmInfo=true + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/excludeFindBugsFilter.xml b/local-test-zookeeper-delta-01/afc-zookeeper/excludeFindBugsFilter.xml new file mode 100644 index 0000000000000000000000000000000000000000..a296594483780c9efd0d67d37f9e73fa56c0d2a5 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/excludeFindBugsFilter.xml @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/owaspSuppressions.xml b/local-test-zookeeper-delta-01/afc-zookeeper/owaspSuppressions.xml new file mode 100644 index 0000000000000000000000000000000000000000..56003dc5b4b9e03271310a62500544623d755a01 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/owaspSuppressions.xml @@ -0,0 +1,80 @@ + + + + + + + + CVE-2024-6763 + + + + CVE-2018-8088 + + + + CVE-2021-37533 + + + + CVE-2018-8012 + + + + CVE-2016-5017 + + + + CVE-2018-12056 + + CVE-2023-4586 + + + + CVE-2019-3826 + + + + + + CVE-2021-29425 + CVE-2021-28164 + CVE-2021-34429 + + + + + + + CVE-2023-35116 + + + CVE-2022-45688 + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..664d8fb0a7051f35b1464a44c447550e25acc500 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/pom.xml @@ -0,0 +1,1238 @@ + + + + 4.0.0 + + org.apache + apache + 23 + + + + org.apache.zookeeper + parent + pom + + 3.10.0-SNAPSHOT + Apache ZooKeeper + + ZooKeeper is a centralized service for maintaining configuration information, naming, + providing distributed synchronization, and providing group services. All of these kinds + of services are used in some form or another by distributed applications. Each time they + are implemented there is a lot of work that goes into fixing the bugs and race conditions + that are inevitable. Because of the difficulty of implementing these kinds of services, + applications initially usually skimp on them ,which make them brittle in the presence of + change and difficult to manage. Even when done correctly, different implementations of + these services lead to management complexity when the applications are deployed. + + http://zookeeper.apache.org + 2008 + + + + Apache License, Version 2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + zookeeper-docs + zookeeper-jute + zookeeper-server + zookeeper-metrics-providers + zookeeper-client + zookeeper-recipes + zookeeper-assembly + zookeeper-compatibility-tests + + + + scm:git:https://gitbox.apache.org/repos/asf/zookeeper.git + scm:git:https://gitbox.apache.org/repos/asf/zookeeper.git + https://gitbox.apache.org/repos/asf/zookeeper.git + HEAD + + + JIRA + http://issues.apache.org/jira/browse/ZOOKEEPER + + + jenkins + https://ci-hadoop.apache.org/view/ZooKeeper/ + + + + User List + user-subscribe@zookeeper.apache.org + user-unsubscribe@zookeeper.apache.org + user@zookeeper.apache.org + http://mail-archives.apache.org/mod_mbox/zookeeper-user/ + + + Developer List + dev-subscribe@zookeeper.apache.org + dev-unsubscribe@zookeeper.apache.org + dev@zookeeper.apache.org + http://mail-archives.apache.org/mod_mbox/zookeeper-dev/ + + + Commits List + commits-subscribe@zookeeper.apache.org + commits-unsubscribe@zookeeper.apache.org + http://mail-archives.apache.org/mod_mbox/zookeeper-commits/ + + + Issues List + issues-subscribe@zookeeper.apache.org + issues-unsubscribe@zookeeper.apache.org + https://lists.apache.org/list.html?issues@zookeeper.apache.org + + + Notifications List + notifications-subscribe@zookeeper.apache.org + notifications-unsubscribe@zookeeper.apache.org + https://lists.apache.org/list.html?notifications@zookeeper.apache.org + + + + + tdunning + Ted Dunning + tdunning@apache.org + -8 + + + camille + Camille Fournier + camille@apache.org + -5 + + + phunt + Patrick Hunt + phunt@apache.org + -8 + + + fpj + Flavio Junqueira + fpj@apache.org + +0 + + + ivank + Ivan Kelly + ivank@apache.org + +2 + + + mahadev + Mahadev Konar + mahadev@apache.org + -8 + + + michim + Michi Mutsuzaki + michim@apache.org + -8 + + + cnauroth + Chris Nauroth + cnauroth@apache.org + -8 + + + breed + Benjamin Reed + breed@apache.org + -8 + + + henry + Henry Robinson + henry@apache.org + -8 + + + rgs + Raul Gutierrez Segales + rgs@apache.org + -8 + + + rakeshr + Rakesh Radhakrishnan + rakeshr@apache.org + +5:30 + + + hanm + Michael Han + hanm@apache.org + -8 + + + gkesavan + Giridharan Kesavan + gkesavan@apache.org + -8 + + + akornev + Andrew Kornev + akornev@apache.org + + + shralex + Alex Shraer + shralex@apache.org + -8 + + + thawan + Thawan Kooburat + thawan@apache.org + -8 + + + hdeng + Hongchao Deng + hdeng@apache.org + -8 + + + arshad + Mohammad Arshad + arshad@apache.org + +5:30 + + + afine + Abraham Fine + afine@apache.org + -8 + + + andor + Andor Molnar + andor@apache.org + +1 + + + lvfangmin + Allan Lyu + fangmin@apache.org + -8 + + + eolivelli + Enrico Olivelli + eolivelli@apache.org + +1 + + + nkalmar + Norbert Kalmar + nkalmar@apache.org + +1 + + + enixon + Brian Nixon + enixon@apache.org + -8 + + + symat + Mate Szalay-Beko + symat@apache.org + +1 + + + ddiederen + Damien Diederen + ddiederen@apache.org + Europe/Berlin + + + maoling + Ling Mao + maoling@apache.org + +8 + + + + + + full-build + + zookeeper-contrib + + zookeeper-it + + + + + fatjar + + zookeeper-contrib + + zookeeper-it + + + + apache-release + + + + org.apache.maven.plugins + maven-assembly-plugin + + + org.apache.apache.resources + apache-source-release-assembly-descriptor + 1.0.6 + + + + + source-release-assembly-tar-gz + initialize + + single + + + true + + + ${sourceReleaseAssemblyDescriptor} + + apache-zookeeper-${project.version} + false + + tar.gz + + posix + + + + + + + + + m2e + + + m2e.version + + + + 8 + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.codehaus.mojo + exec-maven-plugin + [0,) + + exec + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + [0,) + + run + + + + + + + + + com.ruleoftech + markdown-page-generator-plugin + [0,) + + generate + + + + + + + + + org.codehaus.mojo + javacc-maven-plugin + [0,) + + javacc + + + + + + + + + com.github.koraktor + mavanagaiata + [0,) + + commit + + + + + + + + + + + + + + + + jdk-release-flag + + [9,) + + + 8 + + + + clover + + false + + clover + + + + ${project.build.directory}/clover/zookeeper-coverage.db + + + + + org.openclover + clover-maven-plugin + + false + true + ${cloverDatabase} + 50% + ${project.build.directory}/clover + true + false + ${project.build.directory}/clover/zookeeper-coverage.db + ${project.build.directory}/clover/zookeeper-coverage.db + ${project.build.directory}/clover + true + true + false + true + + org/apache/zookeeper/**/* + + + org/apache/zookeeper/version/**/* + **/ReadOnlyModeTest.java + **/KeeperStateTest.java + + + + + clover-setup + process-sources + + setup + + + + clover + test + + clover + + + + + + + + + sonar + + ${project.build.directory}/clover/clover.xml + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + + + + + + org.sonarsource.scanner.maven + sonar-maven-plugin + ${sonar-maven-plugin.version} + + reuseReports + clover + ${project.build.directory}/clover/clover.xml + target/surefire-reports + clover + ${clover-maven-plugin.version} + + + + + + + + + + + 1.8 + 1.8 + 1691130453 + false + 2.22.1 + + 4 + true + + + 2.0.13 + 1.3.14 + 0.12.0 + 1.48 + 5.6.2 + 1.6.2 + 4.9.0 + 2.2 + 1.5.0 + 4.1.115.Final + 9.4.56.v20240826 + 2.15.2 + 2.14.6 + 1.1.10.5 + 2.0.0 + 1.78 + 4.4 + 4.1.12.1 + 4.0.2 + 8.39 + 3.0.0-M3 + 2.17.0 + 0.25.4 + 4.4.1 + 3.7.0.1746 + + + yes + yes + + + + + + + org.hamcrest + hamcrest-library + ${hamcrest.version} + + + org.apache.commons + commons-collections4 + ${commons-collections.version} + + + org.apache.yetus + audience-annotations + ${audience-annotations.version} + + + commons-cli + commons-cli + ${commons-cli.version} + + + org.apache.kerby + kerb-core + ${kerby.version} + + + org.slf4j + slf4j-api + + + + + org.apache.kerby + kerb-simplekdc + ${kerby.version} + + + org.slf4j + slf4j-api + + + + + org.apache.kerby + kerby-config + ${kerby.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + + org.bouncycastle + bcprov-jdk18on + ${bouncycastle.version} + + + org.bouncycastle + bcpkix-jdk18on + ${bouncycastle.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + ch.qos.logback + logback-core + ${logback-version} + + + ch.qos.logback + logback-classic + ${logback-version} + + + org.jmockit + jmockit + ${jmockit.version} + + + org.junit.jupiter + junit-jupiter-api + ${junit.version} + + + org.junit.jupiter + junit-jupiter-engine + ${junit.version} + + + org.junit.jupiter + junit-jupiter-params + ${junit.version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform.version} + test + + + org.junit.vintage + junit-vintage-engine + ${junit.version} + + + org.mockito + mockito-core + ${mockito.version} + + + org.mockito + mockito-inline + ${mockito.version} + test + + + io.netty + netty-bom + ${netty.version} + pom + import + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-servlet + ${jetty.version} + + + org.eclipse.jetty + jetty-client + ${jetty.version} + + + io.dropwizard.metrics + metrics-core + ${dropwizard.version} + + + org.slf4j + slf4j-api + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + jline + jline + ${jline.version} + + + com.github.spotbugs + spotbugs-annotations + ${spotbugsannotations.version} + provided + true + + + org.xerial.snappy + snappy-java + ${snappy.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.burningwave + tools + ${burningwave.mockdns.version} + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + true + + -Werror + -Xlint:deprecation + -Xlint:unchecked + -Xlint:-options + -Xdoclint:-missing + + -Xpkginfo:always + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + ${mvngit.commit.id} + + + + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + true + none + + + + org.apache.maven.plugins + maven-assembly-plugin + 3.6.0 + + + org.apache.maven.plugins + maven-release-plugin + + + org.apache.maven.plugins + maven-scm-plugin + 1.11.2 + + + org.apache.maven.plugins + maven-surefire-plugin + + false + ${redirectTestOutputToFile} + + + + org.apache.maven.plugins + maven-antrun-plugin + + + org.apache.maven.plugins + maven-dependency-plugin + + + org.codehaus.mojo + exec-maven-plugin + 1.6.0 + + + com.github.koraktor + mavanagaiata + 0.9.4 + + true + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + 1.8 + + + org.openclover + clover-maven-plugin + ${clover-maven-plugin.version} + + + com.github.spotbugs + spotbugs-maven-plugin + 4.0.0 + + excludeFindBugsFilter.xml + + + + org.owasp + dependency-check-maven + 8.3.1 + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.1 + + + com.puppycrawl.tools + checkstyle + ${checkstyle.version} + + + + checkstyle-strict.xml + checkstyleSuppressions.xml + UTF-8 + true + true + false + false + true + + + + + maven-remote-resources-plugin + + + process-resource-bundles + none + + + + + org.apache.felix + maven-bundle-plugin + 5.1.9 + + + org.cyclonedx + cyclonedx-maven-plugin + 2.7.9 + + + + + + + com.github.koraktor + mavanagaiata + + + find-current-git-revision + + commit + + validate + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + set-hostname-property + validate + + run + + + true + + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + Jar Tests Package + package + + test-jar + + + + org/** + META_INF/** + + true + + + + + + org.apache.maven.plugins + maven-source-plugin + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + + + attach-javadocs + + jar + + + + aggregate + site + + aggregate + + + + + zookeeper-server/src/main/resources/overview.html + *.recipes.* + + + + + + net.nicoulaj.maven.plugins + checksum-maven-plugin + + + + artifacts + + + + + + SHA-512 + + true + + + + + com.github.spotbugs + spotbugs-maven-plugin + + + org.owasp + dependency-check-maven + + ALL + 0 + + owaspSuppressions.xml + + + + + org.apache.rat + apache-rat-plugin + + + **/README.md + **/findbugsExcludeFile.xml + **/checkstyle-noframes-sorted.xsl + **/configure.ac + **/Makefile.am + conf/zoo_sample.cfg + conf/configuration.xsl + .travis.yml + excludeFindBugsFilter.xml + README_packaging.md + src/main/resources/markdown/skin/* + src/main/resources/markdown/html/* + src/main/resources/markdown/images/* + **/src/test/resources/embedded/*.conf + + **/JMX-RESOURCES + **/src/main/resources/mainClasses + **/Changes + **/MANIFEST + **/src/test/zoo.cfg + **/src/main/resources/webapp/org/apache/zookeeper/graph/resources/* + **/src/main/java/com/nitido/utils/toaster/Toaster.java + **/TODO + + **/acinclude.m4 + **/aminclude.am + **/src/hashtable/* + **/include/winconfig.h + **/tests/wrappers.opt + **/tests/zoo.cfg + **/tests/wrappers-mt.opt + **/c-doc.Doxyfile + + true + + + + org.apache.maven.plugins + maven-release-plugin + false + + + clean verify -DskipTests antrun:run@replace-cclient-files-during-release scm:add@add-cclient-files-during-release scm:checkin@commit-cclient-files-during-release + clean verify -DskipTests antrun:run@replace-cclient-files-during-release scm:add@add-cclient-files-during-release scm:checkin@commit-cclient-files-during-release + false + true + true + release-@{project.version} + + + + org.apache.maven.plugins + maven-scm-plugin + false + + + add-cclient-files-during-release + none + + add + + + false + zookeeper-client/zookeeper-client-c/CMakeLists.txt,zookeeper-client/zookeeper-client-c/configure.ac,zookeeper-client/zookeeper-client-c/include/zookeeper_version.h + + + + commit-cclient-files-during-release + none + + + checkin + + + false + Prepared ${project.version} + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${enforcer.version} + + + banned-commons-lang + + enforce + + + + + + commons-lang:commons-lang + + false + We don't use commons-lang anymore, so do not depend on it directly. + + + + + + banned-commons-lang3 + + enforce + + + + + + org.apache.commons:commons-lang3 + + false + We don't use commons-lang3, so do not depend on it directly. + + + + + + banned-json-simple + + enforce + + + + + + com.googlecode.json-simple:json-simple + + false + We don't use json-simple anymore, so do not depend on it directly. + + + + + + + + org.cyclonedx + cyclonedx-maven-plugin + + + + makeBom + + package + + + + + + + ${project.basedir}src/main/java/resources + + **/*.* + + + + + + + + + org.openclover + clover-maven-plugin + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zk-merge-pr.py b/local-test-zookeeper-delta-01/afc-zookeeper/zk-merge-pr.py new file mode 100644 index 0000000000000000000000000000000000000000..100244bfc16d22e105d23dc469cc9134110fc8fd --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zk-merge-pr.py @@ -0,0 +1,540 @@ +#!/usr/bin/env python + +# +# 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. +# + +# Utility for creating well-formed pull request merges and pushing them to Apache. This script is a modified version +# of the one created by the Spark project (https://github.com/apache/spark/blob/master/dev/merge_spark_pr.py). +# +# Usage: ./zk-merge-pr.py (see config env vars below) +# +# This utility assumes you already have a local ZooKeeper git folder and that you +# have added remotes corresponding to both: +# (i) the github apache ZooKeeper mirror and +# (ii) the apache ZooKeeper git repo. + +import json +import os +import re +import subprocess +import sys +import urllib.request, urllib.error, urllib.parse +import getpass +import requests + +try: + import jira.client + JIRA_IMPORTED = True +except ImportError: + JIRA_IMPORTED = False + +PROJECT_NAME = "zookeeper" + +CAPITALIZED_PROJECT_NAME = PROJECT_NAME.upper() + +# Remote name which points to the GitHub site +PR_REMOTE_NAME = os.environ.get("PR_REMOTE_NAME", "apache-github") +# Remote name which points to Apache git +PUSH_REMOTE_NAME = os.environ.get("PUSH_REMOTE_NAME", "apache") +# ASF JIRA username +JIRA_USERNAME = os.environ.get("JIRA_USERNAME", "") +# ASF JIRA password +JIRA_PASSWORD = os.environ.get("JIRA_PASSWORD", "") +# ASF JIRA access token +# If it is configured, username and password are dismissed +# Go to https://issues.apache.org/jira/secure/ViewProfile.jspa -> Personal Access Tokens for +# your own token management. +JIRA_ACCESS_TOKEN = os.environ.get("JIRA_ACCESS_TOKEN") +# OAuth key used for issuing requests against the GitHub API. If this is not defined, then requests +# will be unauthenticated. You should only need to configure this if you find yourself regularly +# exceeding your IP's unauthenticated request rate limit. You can create an OAuth key at +# https://github.com/settings/tokens. This script only requires the "public_repo" scope. +GITHUB_OAUTH_KEY = os.environ.get("GITHUB_OAUTH_KEY") + +GITHUB_USER = os.environ.get("GITHUB_USER", "apache") +GITHUB_BASE = "https://github.com/%s/%s/pull" % (GITHUB_USER, PROJECT_NAME) +GITHUB_API_BASE = "https://api.github.com/repos/%s/%s" % (GITHUB_USER, PROJECT_NAME) +JIRA_BASE = "https://issues.apache.org/jira/browse" +JIRA_API_BASE = "https://issues.apache.org/jira" +# Prefix added to temporary branches +TEMP_BRANCH_PREFIX = "PR_TOOL" +# TODO Introduce a convention as this is too brittle +RELEASE_BRANCH_PREFIX = "branch-" + +DEV_BRANCH_NAME = "master" + +DEFAULT_FIX_VERSION = os.environ.get("DEFAULT_FIX_VERSION", "branch-3.5") + +def get_json(url): + try: + request = urllib.request.Request(url) + if GITHUB_OAUTH_KEY: + request.add_header('Authorization', 'token %s' % GITHUB_OAUTH_KEY) + return json.load(urllib.request.urlopen(request)) + except urllib.error.HTTPError as e: + if "X-RateLimit-Remaining" in e.headers and e.headers["X-RateLimit-Remaining"] == '0': + print("Exceeded the GitHub API rate limit; see the instructions in " + \ + "zk-merge-pr.py to configure an OAuth token for making authenticated " + \ + "GitHub requests.") + else: + print("Unable to fetch URL, exiting: %s" % url) + sys.exit(-1) + + +def fail(msg): + print(msg) + clean_up() + sys.exit(-1) + + +def run_cmd(cmd): + print(cmd) + if isinstance(cmd, list): + return subprocess.check_output(cmd, encoding='utf8') + else: + return subprocess.check_output(cmd.split(" "), encoding='utf8') + + +def continue_maybe(prompt): + result = input("\n%s (y/n): " % prompt) + if result.lower().strip() != "y": + fail("Okay, exiting") + +def clean_up(): + if original_head != get_current_branch(): + print("Restoring head pointer to %s" % original_head) + run_cmd("git checkout %s" % original_head) + + branches = run_cmd("git branch").replace(" ", "").split("\n") + + for branch in [x for x in branches if x.startswith(TEMP_BRANCH_PREFIX)]: + print("Deleting local branch %s" % branch) + run_cmd("git branch -D %s" % branch) + +def get_current_branch(): + return run_cmd("git rev-parse --abbrev-ref HEAD").replace("\n", "") + +# merge the requested PR and return the merge hash +def merge_pr(pr_num, title, pr_repo_desc): + + merge_message = [] + result = input("Would you like to squash the commit messages? (y/n): ") + if result.lower().strip() == "y": + # Retrieve the commits separately. + json_commits = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/commits") + if json_commits and isinstance(json_commits, list): + for commit in json_commits: + commit_message = commit['commit']['message'] + # Remove empty lines and lines containing "Change-Id:" + filtered_lines = [line for line in commit_message.split('\n') if 'Change-Id:' not in line and line.strip()] + modified_commit_message = '\n'.join(filtered_lines) + if modified_commit_message.strip() != title.strip(): + merge_message += [modified_commit_message] + + # Check for disapproval reviews. + json_reviewers = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/reviews") + disapproval_reviews = [review['user']['login'] for review in json_reviewers if review['state'] == 'CHANGES_REQUESTED'] + if disapproval_reviews: + continue_maybe("Warning: There are requested changes. Proceed with merging pull request #%s?" % pr_num) + # Verify if there are no approved reviews. + approved_reviewers = [review['user']['login'] for review in json_reviewers if review['state'] == 'APPROVED'] + if not approved_reviewers: + continue_maybe("Warning: Pull Request does not have an approved review. Proceed with merging pull request #%s?" % pr_num) + else: + reviewers_string = ', '.join(approved_reviewers) + merge_message += [f"Reviewers: {reviewers_string}"] + # Check the author and the closing line. + json_pr = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}") + primary_author = json_pr["user"]["login"] + if primary_author != "": + merge_message += [f"Author: {primary_author}"] + close_line = "Closes #%s from %s" % (pr_num, pr_repo_desc) + merge_message += [close_line] + merged_string = '\n'.join(merge_message) + + # Get the latest commit SHA. + latest_commit_sha = json_pr["head"]["sha"] + json_status = get_json(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/commits/{latest_commit_sha}/check-runs") + # Check if all checks have passed on GitHub. + all_checks_passed = all(status["conclusion"] == "success" for status in json_status["check_runs"]) + if all_checks_passed: + print("All checks have passed on the github.") + else: + any_in_progress = any(run["status"] == "in_progress" for run in json_status["check_runs"]) + if any_in_progress: + continue_maybe("Warning: There are pending checks. Would you like to continue the merge?") + else: + continue_maybe("Warning: Not all checks have passed on GitHub. Would you like to continue the merge?") + + headers = { + "Authorization": f"token {GITHUB_OAUTH_KEY}", + "Accept": "application/vnd.github.v3+json" + } + data = { + "commit_title": title, + "commit_message": merged_string, + "merge_method": "squash" + } + + response = requests.put(f"https://api.github.com/repos/{PUSH_REMOTE_NAME}/{PROJECT_NAME}/pulls/{pr_num}/merge", headers=headers, json=data) + + if response.status_code == 200: + merge_response_json = response.json() + merge_commit_sha = merge_response_json.get("sha") + print(f"Pull request #{pr_num} merged. Sha: #{merge_commit_sha}") + return merge_commit_sha + else: + print(f"Failed to merge pull request #{pr_num}. Status code: {response.status_code}") + print(response.text) + exit() + +def cherry_pick(pr_num, merge_hash, default_branch): + pick_ref = input("Enter a branch name [%s]: " % default_branch) + if pick_ref == "": + pick_ref = default_branch + + pick_branch_name = "%s_PICK_PR_%s_%s" % (TEMP_BRANCH_PREFIX, pr_num, pick_ref.upper()) + + run_cmd("git fetch %s" % PR_REMOTE_NAME) + run_cmd("git checkout -b %s %s/%s" % (pick_branch_name, PUSH_REMOTE_NAME, pick_ref)) + + current_attempt = 0 + max_attempts = 6 + # Check if the merge hash exists + while not run_cmd("git rev-parse --verify %s" % merge_hash): + if current_attempt >= max_attempts: + print("Error: The commit hash does not exist in the local repository.") + exit() + current_attempt += 1 + print("Waiting for the merge hash to become available...(10 sec)") + time.sleep(10) + run_cmd("git fetch %s" % PR_REMOTE_NAME) + + try: + run_cmd("git cherry-pick -sx %s" % merge_hash) + except Exception as e: + msg = "Error cherry-picking: %s\nWould you like to manually fix-up this merge?" % e + continue_maybe(msg) + msg = "Okay, please fix any conflicts and finish the cherry-pick. Finished?" + continue_maybe(msg) + + continue_maybe("Pick complete (local ref %s). Push to %s?" % ( + pick_branch_name, PUSH_REMOTE_NAME)) + + try: + run_cmd('git push %s %s:%s' % (PUSH_REMOTE_NAME, pick_branch_name, pick_ref)) + except Exception as e: + clean_up() + fail("Exception while pushing: %s" % e) + + pick_hash = run_cmd("git rev-parse %s" % pick_branch_name)[:8] + clean_up() + + print(("Pull request #%s picked into %s!" % (pr_num, pick_ref))) + print(("Pick hash: %s" % pick_hash)) + return pick_ref + + +def fix_version_from_branch(branch, versions): + # Note: Assumes this is a sorted (newest->oldest) list of un-released versions + if branch == DEV_BRANCH_NAME: + versions = [x for x in versions if x == DEFAULT_FIX_VERSION] + if len(versions) > 0: + return versions[0] + else: + return None + else: + versions = [x for x in versions if x.startswith(branch)] + if len(versions) > 0: + return versions[-1] + else: + return None + + +def resolve_jira_issue(merge_branches, comment, default_jira_id=""): + jira_server = {"server": JIRA_API_BASE} + + if JIRA_ACCESS_TOKEN is not None: + asf_jira = jira.client.JIRA(jira_server, token_auth=JIRA_ACCESS_TOKEN) + else: + asf_jira = jira.client.JIRA(jira_server, basic_auth=(JIRA_USERNAME, JIRA_PASSWORD)) + + jira_id = input("Enter a JIRA id [%s]: " % default_jira_id) + if jira_id == "": + jira_id = default_jira_id + + try: + issue = asf_jira.issue(jira_id) + except Exception as e: + fail("ASF JIRA could not find %s\n%s" % (jira_id, e)) + + cur_status = issue.fields.status.name + cur_summary = issue.fields.summary + cur_assignee = issue.fields.assignee + if cur_assignee is None: + cur_assignee = "NOT ASSIGNED!!!" + else: + cur_assignee = cur_assignee.displayName + + if cur_status == "Resolved" or cur_status == "Closed": + fail("JIRA issue %s already has status '%s'" % (jira_id, cur_status)) + print(("=== JIRA %s ===" % jira_id)) + print(("summary\t\t%s\nassignee\t%s\nstatus\t\t%s\nurl\t\t%s/%s\n" % ( + cur_summary, cur_assignee, cur_status, JIRA_BASE, jira_id))) + + versions = asf_jira.project_versions(CAPITALIZED_PROJECT_NAME) + versions = sorted(versions, key=lambda x: x.name, reverse=True) + versions = [x for x in versions if x.raw['released'] is False] + + version_names = [x.name for x in versions] + default_fix_versions = [fix_version_from_branch(x, version_names) for x in merge_branches] + default_fix_versions = [x for x in default_fix_versions if x != None] + default_fix_versions = ",".join(default_fix_versions) + + fix_versions = input("Enter comma-separated fix version(s) [%s]: " % default_fix_versions) + if fix_versions == "": + fix_versions = default_fix_versions + fix_versions = fix_versions.replace(" ", "").split(",") + + def get_version_json(version_str): + return [v for v in versions if v.name == version_str][0].raw + + jira_fix_versions = [get_version_json(v) for v in fix_versions] + + resolve = [a for a in asf_jira.transitions(jira_id) if a['name'] == "Resolve Issue"][0] + resolution = [r for r in asf_jira.resolutions() if r.raw['name'] == "Fixed"][0] + asf_jira.transition_issue( + jira_id, resolve["id"], fixVersions = jira_fix_versions, + comment = comment, resolution = {'id': resolution.raw['id']}) + + print("Successfully resolved %s with fixVersions=%s!" % (jira_id, fix_versions)) + + +def resolve_jira_issues(title, merge_branches, comment): + jira_ids = re.findall("%s-[0-9]+" % CAPITALIZED_PROJECT_NAME, title) + + if len(jira_ids) == 0: + resolve_jira_issue(merge_branches, comment) + for jira_id in jira_ids: + resolve_jira_issue(merge_branches, comment, jira_id) + + +def standardize_jira_ref(text): + """ + Standardize the jira reference commit message prefix to "PROJECT_NAME-XXX: Issue" + + >>> standardize_jira_ref("%s-5954: Top by key" % CAPITALIZED_PROJECT_NAME) + 'ZOOKEEPER-5954: Top by key' + >>> standardize_jira_ref("%s-5821: ParquetRelation2 CTAS should check if delete is successful" % PROJECT_NAME) + 'ZOOKEEPER-5821: ParquetRelation2 CTAS should check if delete is successful' + >>> standardize_jira_ref("%s-4123: [WIP] Show new dependencies added in pull requests" % PROJECT_NAME) + 'ZOOKEEPER-4123: [WIP] Show new dependencies added in pull requests' + >>> standardize_jira_ref("%s 5954: Top by key" % PROJECT_NAME) + 'ZOOKEEPER-5954: Top by key' + >>> standardize_jira_ref("%s-979: a LRU scheduler for load balancing in TaskSchedulerImpl" % PROJECT_NAME) + 'ZOOKEEPER-979: a LRU scheduler for load balancing in TaskSchedulerImpl' + >>> standardize_jira_ref("%s-1094: Support MiMa for reporting binary compatibility across versions." % CAPITALIZED_PROJECT_NAME) + 'ZOOKEEPER-1094: Support MiMa for reporting binary compatibility across versions.' + >>> standardize_jira_ref("%s-1146: [WIP] Vagrant support" % CAPITALIZED_PROJECT_NAME) + 'ZOOKEEPER-1146: [WIP] Vagrant support' + >>> standardize_jira_ref("%s-1032: If Yarn app fails before registering, app master stays aroun..." % PROJECT_NAME) + 'ZOOKEEPER-1032: If Yarn app fails before registering, app master stays aroun...' + >>> standardize_jira_ref("%s-6250 %s-6146 %s-5911: Types are now reserved words in DDL parser." % (PROJECT_NAME, PROJECT_NAME, CAPITALIZED_PROJECT_NAME)) + 'ZOOKEEPER-6250 ZOOKEEPER-6146 ZOOKEEPER-5911: Types are now reserved words in DDL parser.' + >>> standardize_jira_ref("Additional information for users building from source code") + 'Additional information for users building from source code' + """ + jira_refs = [] + components = [] + + # Extract JIRA ref(s): + pattern = re.compile(r'(%s[-\s]*[0-9]{3,6})+' % CAPITALIZED_PROJECT_NAME, re.IGNORECASE) + for ref in pattern.findall(text): + # Add brackets, replace spaces with a dash, & convert to uppercase + jira_refs.append(re.sub(r'\s+', '-', ref.upper())) + text = text.replace(ref, '') + + # Extract project name component(s): + # Look for alphanumeric chars, spaces, dashes, periods, and/or commas + pattern = re.compile(r'(\[[\w\s,-\.]+\])', re.IGNORECASE) + for component in pattern.findall(text): + components.append(component.upper()) + text = text.replace(component, '') + + # Cleanup any remaining symbols: + pattern = re.compile(r'^\W+(.*)', re.IGNORECASE) + if (pattern.search(text) is not None): + text = pattern.search(text).groups()[0] + + # Assemble full text (JIRA ref(s), module(s), remaining text) + jira_prefix = ' '.join(jira_refs).strip() + if jira_prefix: + jira_prefix = jira_prefix + ": " + clean_text = jira_prefix + ' '.join(components).strip() + " " + text.strip() + + # Replace multiple spaces with a single space, e.g. if no jira refs and/or components were included + clean_text = re.sub(r'\s+', ' ', clean_text.strip()) + + return clean_text + +def get_remote_repos(): + repos = run_cmd("git remote -v").split() + + dict = {} + for i in range(0, len(repos), 3): + dict[repos[i]] = repos[i+1] + return dict + + +def check_git_remote(): + repos = get_remote_repos() + + # check if all remote endpoints' URLs point to project git repo + name = PROJECT_NAME + ".git" + for url in list(repos.values()): + if not url.endswith(name): + fail("Error: not a %s git repo or at least one remote is invalid" % PROJECT_NAME) + + if not PR_REMOTE_NAME in repos: + fail("Error: PR_REMOTE_NAME (%s) environment variable has not been set!" % PR_REMOTE_NAME) + + if not PUSH_REMOTE_NAME in repos: + fail("Error: PUSH_REMOTE_NAME (%s) environment variable has not been set!" % PUSH_REMOTE_NAME) + + +def check_jira_env(): + + global JIRA_PASSWORD + + if JIRA_IMPORTED: + if JIRA_ACCESS_TOKEN is None: + if JIRA_USERNAME.strip() != "" and JIRA_PASSWORD.strip() == "": + inform_pwd = input("JIRA_USERNAME set but JIRA_PASSWORD is not. Want to inform it? ") + if inform_pwd.strip() == "y": + JIRA_PASSWORD = getpass.getpass('JIRA PASSWORD: ') + + if JIRA_USERNAME.strip() == "" or JIRA_PASSWORD.strip() == "": + msg ="Neither JIRA_ACCESS_TOKEN nor JIRA_USERNAME and/or JIRA_PASSWORD are set. Want to continue? " + continue_maybe(msg) + else: + msg = "JIRA lib not installed. Want to continue? " + continue_maybe(msg) + +def main(): + global original_head + + original_head = get_current_branch() + + check_jira_env() + + check_git_remote() + + branches = get_json("%s/branches" % GITHUB_API_BASE) + branch_names = [x for x in [x['name'] for x in branches] if x.startswith(RELEASE_BRANCH_PREFIX)] + # Assumes branch names can be sorted lexicographically + latest_branch = sorted(branch_names, reverse=True)[0] + + pr_num = input("Which pull request would you like to merge? (e.g. 34): ") + pr = get_json("%s/pulls/%s" % (GITHUB_API_BASE, pr_num)) + + # Check if the pull request has already been closed or merged. + pull_request_state = pr.get("state", "") + if pull_request_state == "closed": + merge_hash = pr.get("merge_commit_sha", "") + merged = pr.get("merged") + # Verify if the pull request has been merged by the GitHub API. + if merged is True: + print(f"Pull request #{pr['number']} has already been merged, assuming you want to backport") + cherry_pick(pr_num, merge_hash, latest_branch) + sys.exit(0) + # Some merged pull requests may not appear as merged in the GitHub API, + # for example, those closed by an older version of this script. + else: + pr_events = get_json("%s/issues/%s/events" % (GITHUB_API_BASE, pr_num)) + for event in pr_events: + if event.get("event") == "closed": + commit_id = event.get("commit_id") + if commit_id is not None: + print(f"Pull request #{pr['number']} has already been merged, assuming you want to backport") + cherry_pick(pr_num, merge_hash, latest_branch) + sys.exit(0) + else: + print(f"Pull request #{pr['number']} has already been closed, but not merged, exiting.") + exit() + + if not bool(pr["mergeable"]): + print(f"Pull request %s is not mergeable in its current form.\n" % pr_num) + exit() + + url = pr["url"] + + pr_title = pr["title"] + commit_title = input("Commit title [%s]: " % pr_title) + if commit_title == "": + commit_title = pr_title + + # Decide whether to use the modified title or not + modified_title = standardize_jira_ref(commit_title) + if modified_title != commit_title: + print("I've re-written the title as follows to match the standard format:") + print("Original: %s" % commit_title) + print("Modified: %s" % modified_title) + result = input("Would you like to use the modified title? (y/n): ") + if result.lower().strip() == "y": + commit_title = modified_title + print("Using modified title:") + else: + print("Using original title:") + print(commit_title) + + target_ref = pr["base"]["ref"] + user_login = pr["user"]["login"] + base_ref = pr["head"]["ref"] + pr_repo_desc = "%s/%s" % (user_login, base_ref) + + print(("\n=== Pull Request #%s ===" % pr_num)) + print(("PR title\t%s\nCommit title\t%s\nSource\t\t%s\nTarget\t\t%s\nURL\t\t%s" % ( + pr_title, commit_title, pr_repo_desc, target_ref, url))) + continue_maybe("Proceed with merging pull request #%s?" % pr_num) + + merged_refs = [target_ref] + + merge_hash = merge_pr(pr_num, commit_title, pr_repo_desc) + + pick_prompt = "Would you like to pick %s into another branch?" % merge_hash + while input("\n%s (y/n): " % pick_prompt).lower().strip() == "y": + merged_refs = merged_refs + [cherry_pick(pr_num, merge_hash, latest_branch)] + + if JIRA_IMPORTED: + if (JIRA_ACCESS_TOKEN is not None) or (JIRA_USERNAME and JIRA_PASSWORD): + continue_maybe("Would you like to update an associated JIRA?") + jira_comment = "Issue resolved by pull request %s\n[%s/%s]" % (pr_num, GITHUB_BASE, pr_num) + resolve_jira_issues(commit_title, merged_refs, jira_comment) + else: + print("Neither JIRA_ACCESS_TOKEN nor JIRA_USERNAME and/or JIRA_PASSWORD are set.") + print("Exiting without trying to close the associated JIRA.") + else: + print("Could not find jira-python library. Run 'sudo pip install jira' to install.") + print("Exiting without trying to close the associated JIRA.") + +if __name__ == "__main__": + import doctest + (failure_count, test_count) = doctest.testmod() + if (failure_count): + exit(-1) + + main() diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-assembly/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-assembly/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..160f9e1b9d0f5bf517cf6d7cb66f7fcc899c9930 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-assembly/pom.xml @@ -0,0 +1,178 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-assembly + pom + Apache ZooKeeper - Assembly + ZooKeeper Assembly + + + + full-build + + false + + + + + + + 0644 + 0755 + true + + + + + org.apache.zookeeper + zookeeper-docs + ${project.version} + pom + + + org.apache.zookeeper + zookeeper-jute + ${project.version} + + + org.apache.zookeeper + zookeeper + ${project.version} + + + org.apache.zookeeper + zookeeper-client + ${project.version} + pom + + + org.apache.zookeeper + zookeeper-prometheus-metrics + ${project.version} + + + org.apache.zookeeper + zookeeper-recipes + ${project.version} + pom + + + + commons-cli + commons-cli + + + org.eclipse.jetty + jetty-server + + + org.eclipse.jetty + jetty-servlet + + + com.fasterxml.jackson.core + jackson-databind + + + jline + jline + + + ch.qos.logback + logback-classic + + + io.dropwizard.metrics + metrics-core + + + org.xerial.snappy + snappy-java + + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + + bin-assembly + package + + single + + + + ${project.basedir}/src/main/assembly/bin-package.xml + + apache-zookeeper-${project.version}-bin + false + posix + + + + lib-assembly + package + + single + + + + ${project.basedir}/src/main/assembly/lib-package.xml + + apache-zookeeper-${project.version}-lib + false + posix + ${skip.lib.artifact} + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + true + + + + + maven-deploy-plugin + + + true + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-client/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-client/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..16f6419f6d25e8276a2d0079f31eba51e5c04c62 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-client/pom.xml @@ -0,0 +1,53 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-client + pom + Apache ZooKeeper - Client + ZooKeeper client + + + + full-build + + zookeeper-client-c + + + + + + + maven-deploy-plugin + + + true + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-compatibility-tests/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-compatibility-tests/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..2d85a16ad7df414879599e0d51abcb1be7d34f41 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-compatibility-tests/pom.xml @@ -0,0 +1,58 @@ + + + + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + pom + 4.0.0 + + zookeeper-compatibility-tests + + + zookeeper-compatibility-tests-curator + + + Apache ZooKeeper - Compatibility Tests + Module for various compatibility tests + + + + + org.apache.maven.plugins + maven-install-plugin + + true + + + + + org.apache.maven.plugins + maven-deploy-plugin + + true + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build-contrib.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build-contrib.xml new file mode 100644 index 0000000000000000000000000000000000000000..34f3c9b03b3e5258b9f58835b58d6643d48613aa --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build-contrib.xml @@ -0,0 +1,233 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build.xml new file mode 100644 index 0000000000000000000000000000000000000000..bfb6f66ccad8d085845382d761f3a606119b63d0 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/build.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/ivysettings.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/ivysettings.xml new file mode 100644 index 0000000000000000000000000000000000000000..15c98b6ec4e63eaaeab7caf68aff56cff2d9681f --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/ivysettings.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..0dc8e867da4965cfdfce2ec96a095d69208e968b --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-contrib/pom.xml @@ -0,0 +1,84 @@ + + + + 4.0.0 + + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-contrib + pom + Apache ZooKeeper - Contrib + + Contrib projects to Apache ZooKeeper + + + + true + + + + + full-build + + zookeeper-contrib-fatjar + zookeeper-contrib-loggraph + zookeeper-contrib-rest + zookeeper-contrib-zooinspector + + + + fatjar + + zookeeper-contrib-fatjar + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + -Xlint:none + + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle-simple.xml + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-docs/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-docs/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..9fd096092b56e2f125fcb9168b94131486bc3706 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-docs/pom.xml @@ -0,0 +1,64 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-docs + Apache ZooKeeper - Documentation + Documentation + pom + + + + + com.ruleoftech + markdown-page-generator-plugin + 2.1.0 + + + process-sources + + generate + + + + + ${project.basedir}/src/main/resources/markdown/html/header.html + ${project.basedir}/src/main/resources/markdown/html/footer.html + images,skin + TABLES,FENCED_CODE_BLOCKS + + + + maven-deploy-plugin + + + true + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/README.txt b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c4b1cc4865e4e720137bc69f9c4d25809a8141b --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/README.txt @@ -0,0 +1,63 @@ +To run the system test we need to create processing containers that we can +spawn tasks, called Instances, in. (how is that for a dangling preposition!?!) +Start up InstanceContainers first. Then run the system test. The system test +finds the InstanceContainers and directs them through ZooKeeper, so you are +going to need an instance of ZooKeeper running that they can all access. +The easiest way to do all of this is to use the zookeeper fat jar. + +Steps to run system test +------------------------ +1) build and transfer the fatjar from the `zookeeper-contrib/zookeeper-contrib-fatjar/target` + directory to all systems participating in the test + + Command to build fatjar without executing the tests: + + `mvn clean install -P fatjar -DskipTests` + +2) run a zookeeper standalone instance (cluster is ok too) + +e.g. java -jar zookeeper--fatjar.jar server + +Note: you must provide zoo.cfg, see sample in conf directory + +3) on each host start the system test container + +e.g. java -jar zookeeper--fatjar.jar ic /sysTest + +name : name of the test container - must be unique + typically it's a good idea to name after the host to aid debugging + +zkHostPort : the host:port of the server from step 2) + +4) initiate the system test using the fatjar: + +java -jar build/contrib/fatjar/zookeeper--fatjar.jar systest org.apache.zookeeper.test.system.SimpleSysTest + +by default it will access the zk server started in 2) on localhost:2181 + +or you can specify a remote host:port using + -DsysTest.zkHostPort=:,:,... + +java -DsysTest.zkHostPort=hostA:2181 -jar build/contrib/fatjar/zookeeper--fatjar.jar systest org.apache.zookeeper.test.system.SimpleSysTest + +where hostA is running the zk server started in step 2) above + +InstanceContainers can also be used to run a the saturation benchmark. The +first two steps are the same as the system test. Step 3 is almost the same: + +3) start the InstanceContainer on each host: + +e.g. java -jar zookeeper--fatjar.jar ic + +note prefix can be /sysTest or any other path. If you do use /sysTest, make +sure the system test isn't running when you run the benchmark. + +4) run GenerateLoad using the following + +java -jar build/contrib/fatjar/zookeeper--fatjar.jar generateLoad #servers #clients + +Once GenerateLoad is started, it will read commands from stdin. Usually +the only command you need to know is "percentage" which sets the percentage +of writes to use in the requests. Once a percentage is set, the benchmark +will start. "percentage 0" will cause only reads to be issued and +"percentage 100" will cause only writes to be issued. diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..0346bd90d64c6aed67c248c594e69b8fc9ee8c28 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-it/pom.xml @@ -0,0 +1,86 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-it + jar + Apache ZooKeeper - Tests + + ZooKeeper system tests + + + + + true + true + true + + + + + org.apache.zookeeper + zookeeper + ${project.version} + + + org.apache.zookeeper + zookeeper + tests + test-jar + ${project.version} + + + org.junit.vintage + junit-vintage-engine + + + org.openjdk.jmh + jmh-core + 1.23 + + + org.openjdk.jmh + jmh-generator-annprocess + 1.23 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${project.basedir}/src/main/java/ + ${project.build.directory}/classes/ + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-jute/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-jute/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..2be9787d5308c97d70b3ed4cdc82df83a32817a8 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-jute/pom.xml @@ -0,0 +1,188 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-jute + jar + Apache ZooKeeper - Jute + ZooKeeper jute + + + + org.apache.yetus + audience-annotations + + + org.junit.jupiter + junit-jupiter-engine + test + + + + + + + org.codehaus.mojo + javacc-maven-plugin + 2.6 + + + generate-sources + javacc + + javacc + + + ${project.basedir}/src/main/java/org/apache/jute/compiler/generated/ + + rcc.jj + + 2 + false + ${project.build.directory}/generated-sources/java + + + + + + maven-compiler-plugin + + + pre-compile-jute + generate-sources + + compile + + + + + + org.codehaus.mojo + exec-maven-plugin + + + generate-Java-Jute + generate-sources + + exec + + + ${project.build.directory}/generated-sources/java + java + + -classpath + + org.apache.jute.compiler.generated.Rcc + -l + java + ${project.basedir}/src/main/resources/zookeeper.jute + + + + + generate-C-Jute + generate-sources + + exec + + + ${project.basedir}/../zookeeper-client/zookeeper-client-c/generated/ + java + + -classpath + + org.apache.jute.compiler.generated.Rcc + -l + c + ${project.basedir}/src/main/resources/zookeeper.jute + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + jute-as-dependency + generate-sources + + add-source + + + + ${basedir}/target/generated-sources/java + + + + + + + + com.github.spotbugs + spotbugs-maven-plugin + + true + + + + org.apache.felix + maven-bundle-plugin + + + build bundle + package + + bundle + + + + + + + *;resolution:=optional + + + org.apache.zookeeper.data, + org.apache.zookeeper.proto, + org.apache.zookeeper.txn, + !org.apache.zookeeper*, + org.apache.jute* + + ZooKeeper Jute Bundle + https://zookeeper.apache.org/doc/current/ + ${mvngit.commit.id} + !Implementation-Build,* + + osgi + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-metrics-providers/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-metrics-providers/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..054763d003a0a6f2f4cdb572b4189abcf9df76d7 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-metrics-providers/pom.xml @@ -0,0 +1,38 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-metrics-providers + pom + Apache ZooKeeper - Metrics Providers + ZooKeeper Metrics Providers + + + zookeeper-prometheus-metrics + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/README.txt b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc788741d635937e801c60fe78233d6ad1b6d9f5 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/README.txt @@ -0,0 +1,26 @@ +1) This source directory contains various Zookeeper recipe implementations. + +2) The recipe directory name should specify the name of the recipe you are implementing - eg. zookeeper-recipes-lock/. + +3) It would be great if you can provide both the java and c recipes for the zookeeper recipes. + C recipes go in to zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/c + Java implementation goes into zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/java. + +4) The recipes hold high standards like our zookeeper c/java libraries, so make sure that you include +some unit testing with both the c and java recipe code. + +5) Also, please name your c client public methods as +zkr_recipe-name_methodname +(eg. zkr_lock_lock in zookeeper-recipes-lock/src/c) + +6) The various recipes are in ../docs/recipes.html or +../../docs/reciped.pdf. Also, this is not an exhaustive list by any chance. +Zookeeper is used (and can be used) for more than what we have listed in the docs. + +7) To run the c tests in all the recipes, +- make sure the main zookeeper c libraries in +{top}/src/c/ are compiled. Run autoreconf -if;./configure; make. The libraries +will be installed in {top}/src/c/.libs. +- run autoreconf if;./configure;make run-check + in zookeeper-recipes/$recipename/src/c + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build-recipes.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build-recipes.xml new file mode 100644 index 0000000000000000000000000000000000000000..d5bf87e15446632f3ab1e1e30dd14cc9b5cdf117 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build-recipes.xml @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build.xml new file mode 100644 index 0000000000000000000000000000000000000000..559d5a53858045f52873f3797475c033308cc654 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/build.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..65a63d64156fced099b644e875be35eeb47925dd --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-recipes/pom.xml @@ -0,0 +1,112 @@ + + + + 4.0.0 + + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper-recipes + pom + Apache ZooKeeper - Recipes + + 1) This module contains various Zookeeper recipe implementations. + + 2) The recipe directory name should specify the name of the recipe you are implementing - eg. zookeeper-recipes-lock. + + 3) It would be great if you can provide both the java and c recipes for the zookeeper recipes. + C recipes go in to zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/c + Java implementation goes into zookeeper-recipes/zookeeper-recipes-[recipe-name]/src/java. + + 4) The recipes hold high standards like our zookeeper c/java libraries, so make sure that you include + some unit testing with both the c and java recipe code. + + 5) Also, please name your c client public methods as + zkr_recipe-name_methodname + (eg. zkr_lock_lock in zookeeper-recipes-lock/src/c) + + 6) To run the c tests in all the recipes, + - make sure the main zookeeper c libraries in + zookeeper-client-c are compiled. Run autoreconf -if;./configure; make. The libraries + will be installed in {top}/src/c/.libs. + - run autoreconf if;./configure;make run-check + in zookeeper-recipes/$recipename/src/c + + + + + zookeeper-recipes-election + zookeeper-recipes-lock + zookeeper-recipes-queue + + + + + org.apache.zookeeper + zookeeper + ${project.version} + + + org.apache.zookeeper + zookeeper + ${project.version} + test-jar + test + + + org.xerial.snappy + snappy-java + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + io.dropwizard.metrics + metrics-core + test + + + com.github.spotbugs + spotbugs-annotations + provided + true + + + + + + + maven-deploy-plugin + + + true + + + + + + \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-server/pom.xml b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-server/pom.xml new file mode 100644 index 0000000000000000000000000000000000000000..327a67f00ce85fc79ece4ca4d236743dc1bc7058 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-server/pom.xml @@ -0,0 +1,352 @@ + + + + 4.0.0 + + org.apache.zookeeper + parent + 3.10.0-SNAPSHOT + + + zookeeper + jar + Apache ZooKeeper - Server + ZooKeeper server + + + + com.github.spotbugs + spotbugs-annotations + provided + true + + + org.hamcrest + hamcrest-library + test + + + org.apache.commons + commons-collections4 + test + + + org.apache.zookeeper + zookeeper-jute + ${project.version} + + + commons-cli + commons-cli + provided + + + org.apache.yetus + audience-annotations + + + io.netty + netty-handler + + + io.netty + netty-transport-native-epoll + linux-x86_64 + + + io.netty + netty-tcnative-boringssl-static + + + org.slf4j + slf4j-api + + + ch.qos.logback + logback-classic + runtime + true + + + org.eclipse.jetty + jetty-server + provided + + + org.eclipse.jetty + jetty-servlet + provided + + + org.eclipse.jetty + jetty-client + provided + + + com.fasterxml.jackson.core + jackson-databind + provided + + + org.bouncycastle + bcprov-jdk18on + test + + + org.bouncycastle + bcpkix-jdk18on + test + + + jline + jline + provided + + + io.dropwizard.metrics + metrics-core + provided + + + org.apache.kerby + kerb-core + test + + + org.apache.kerby + kerb-simplekdc + test + + + org.apache.kerby + kerby-config + test + + + org.mockito + mockito-core + test + + + org.mockito + mockito-inline + test + + + org.jmockit + jmockit + test + + + org.junit.jupiter + junit-jupiter-api + test + + + org.junit.jupiter + junit-jupiter-engine + test + + + org.junit.jupiter + junit-jupiter-params + test + + + org.junit.platform + junit-platform-runner + test + + + org.burningwave + tools + test + + + org.xerial.snappy + snappy-java + provided + + + commons-io + commons-io + compile + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + + build-time + + timestamp-property + + + build.time + yyyy-MM-dd HH:mm zz + en_US + UTC + + + + parse-version + + parse-version + + + + generate-sources + + add-source + + + + ${project.build.directory}/generated-sources/java + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + prepare-filtered-java-source + + copy-resources + + generate-sources + + ${project.build.directory}/generated-sources/java + + + src/main/java-filtered + true + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-dependencies + process-test-resources + + copy-dependencies + + + ${project.build.directory}/lib + false + true + false + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + + **/*Test.java + + ${surefire-forkcount} + false + -Xmx512m -Dtest.junit.threads=${surefire-forkcount} -Dzookeeper.junit.threadid=${surefire.forkNumber} -javaagent:${project.build.directory}/lib/jmockit-1.48.jar + ${project.basedir} + + ${project.build.directory}/surefire + super:D/InIHSb7yEEbrWz8b9l71RjZJU= + + + + + + org.apache.felix + maven-bundle-plugin + + + build bundle + package + + bundle + + + + + + + io.netty.buffer;resolution:=optional, + io.netty.channel;resolution:=optional, + io.netty.channel.group;resolution:=optional, + io.netty.channel.socket.nio;resolution:=optional, + javax.management;resolution:=optional, + javax.security.auth.callback, + javax.security.auth.login, + javax.security.sasl, + org.ietf.jgss, + org.osgi.framework;resolution:=optional, + org.osgi.util.tracker;resolution:=optional, + org.slf4j, + *;resolution:=optional + + + !org.apache.zookeeper.data, + !org.apache.zookeeper.proto, + !org.apache.zookeeper.txn, + org.apache.zookeeper* + + ZooKeeper Bundle + https://zookeeper.apache.org/doc/current/ + ${mvngit.commit.id} + !Implementation-Build,* + + osgi + + + + + org.apache.maven.plugins + maven-jar-plugin + + + publish-test-jar + + test-jar + + + + + + + + diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/Zab.tla b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/Zab.tla new file mode 100644 index 0000000000000000000000000000000000000000..4913f0012ebe5140eacaff65c8f3bf74212a3c66 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/Zab.tla @@ -0,0 +1,1251 @@ +(* + * 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. + *) + +-------------------------------- MODULE Zab --------------------------------- +(* This is the formal specification for the Zab consensus algorithm, + in DSN'2011, which represents protocol specification in our work.*) +EXTENDS Integers, FiniteSets, Sequences, Naturals, TLC +----------------------------------------------------------------------------- +\* The set of servers +CONSTANT Server +\* States of server +CONSTANTS LOOKING, FOLLOWING, LEADING +\* Zab states of server +CONSTANTS ELECTION, DISCOVERY, SYNCHRONIZATION, BROADCAST +\* Message types +CONSTANTS CEPOCH, NEWEPOCH, ACKEPOCH, NEWLEADER, ACKLD, COMMITLD, PROPOSE, ACK, COMMIT +\* [MaxTimeoutFailures, MaxTransactionNum, MaxEpoch, MaxRestarts] +CONSTANT Parameters + +MAXEPOCH == 10 +NullPoint == CHOOSE p: p \notin Server +Quorums == {Q \in SUBSET Server: Cardinality(Q)*2 > Cardinality(Server)} +----------------------------------------------------------------------------- +\* Variables that all servers use. +VARIABLES state, \* State of server, in {LOOKING, FOLLOWING, LEADING}. + zabState, \* Current phase of server, in + \* {ELECTION, DISCOVERY, SYNCHRONIZATION, BROADCAST}. + acceptedEpoch, \* Epoch of the last LEADERINFO packet accepted, + \* namely f.p in paper. + currentEpoch, \* Epoch of the last NEWLEADER packet accepted, + \* namely f.a in paper. + history, \* History of servers: sequence of transactions, + \* containing: [zxid, value, ackSid, epoch]. + lastCommitted \* Maximum index and zxid known to be committed, + \* namely 'lastCommitted' in Leader. Starts from 0, + \* and increases monotonically before restarting. + +\* Variables only used for leader. +VARIABLES learners, \* Set of servers leader connects. + cepochRecv, \* Set of learners leader has received CEPOCH from. + \* Set of record [sid, connected, epoch], + \* where epoch means f.p from followers. + ackeRecv, \* Set of learners leader has received ACKEPOCH from. + \* Set of record + \* [sid, connected, peerLastEpoch, peerHistory], + \* to record f.a and h(f) from followers. + ackldRecv, \* Set of learners leader has received ACKLD from. + \* Set of record [sid, connected]. + sendCounter \* Count of txns leader has broadcast. + +\* Variables only used for follower. +VARIABLES connectInfo \* If follower has connected with leader. + \* If follower lost connection, then null. + +\* Variable representing oracle of leader. +VARIABLE leaderOracle \* Current oracle. + +\* Variables about network channel. +VARIABLE msgs \* Simulates network channel. + \* msgs[i][j] means the input buffer of server j + \* from server i. + +\* Variables only used in verifying properties. +VARIABLES epochLeader, \* Set of leaders in every epoch. + proposalMsgsLog, \* Set of all broadcast messages. + violatedInvariants \* Check whether there are conditions + \* contrary to the facts. + +\* Variable used for recording critical data, +\* to constrain state space or update values. +VARIABLE recorder \* Consists: members of Parameters and pc, values. + \* Form is record: + \* [pc, nTransaction, maxEpoch, nTimeout, nRestart, nClientRequest] + +serverVars == <> + +leaderVars == <> + +followerVars == connectInfo + +electionVars == leaderOracle + +msgVars == msgs + +verifyVars == <> + +vars == <> +----------------------------------------------------------------------------- +\* Return the maximum value from the set S +Maximum(S) == IF S = {} THEN -1 + ELSE CHOOSE n \in S: \A m \in S: n >= m +\* Return the minimum value from the set S +Minimum(S) == IF S = {} THEN -1 + ELSE CHOOSE n \in S: \A m \in S: n <= m + +\* Check server state +IsLeader(s) == state[s] = LEADING +IsFollower(s) == state[s] = FOLLOWING +IsLooking(s) == state[s] = LOOKING + +\* Check if s is a quorum +IsQuorum(s) == s \in Quorums + +IsMyLearner(i, j) == j \in learners[i] +IsMyLeader(i, j) == connectInfo[i] = j +HasNoLeader(i) == connectInfo[i] = NullPoint +HasLeader(i) == connectInfo[i] /= NullPoint +----------------------------------------------------------------------------- +\* FALSE: zxid1 <= zxid2; TRUE: zxid1 > zxid2 +ZxidCompare(zxid1, zxid2) == \/ zxid1[1] > zxid2[1] + \/ /\ zxid1[1] = zxid2[1] + /\ zxid1[2] > zxid2[2] + +ZxidEqual(zxid1, zxid2) == zxid1[1] = zxid2[1] /\ zxid1[2] = zxid2[2] + +TxnZxidEqual(txn, z) == txn.zxid[1] = z[1] /\ txn.zxid[2] = z[2] + +TxnEqual(txn1, txn2) == /\ ZxidEqual(txn1.zxid, txn2.zxid) + /\ txn1.value = txn2.value + +EpochPrecedeInTxn(txn1, txn2) == txn1.zxid[1] < txn2.zxid[1] +----------------------------------------------------------------------------- +\* Actions about recorder +GetParameter(p) == IF p \in DOMAIN Parameters THEN Parameters[p] ELSE 0 +GetRecorder(p) == IF p \in DOMAIN recorder THEN recorder[p] ELSE 0 + +RecorderGetHelper(m) == (m :> recorder[m]) +RecorderIncHelper(m) == (m :> recorder[m] + 1) + +RecorderIncTimeout == RecorderIncHelper("nTimeout") +RecorderGetTimeout == RecorderGetHelper("nTimeout") +RecorderIncRestart == RecorderIncHelper("nRestart") +RecorderGetRestart == RecorderGetHelper("nRestart") +RecorderSetTransactionNum(pc) == ("nTransaction" :> + IF pc[1] = "LeaderProcessRequest" THEN + LET s == CHOOSE i \in Server: + \A j \in Server: Len(history'[i]) >= Len(history'[j]) + IN Len(history'[s]) + ELSE recorder["nTransaction"]) +RecorderSetMaxEpoch(pc) == ("maxEpoch" :> + IF pc[1] = "LeaderProcessCEPOCH" THEN + LET s == CHOOSE i \in Server: + \A j \in Server: acceptedEpoch'[i] >= acceptedEpoch'[j] + IN acceptedEpoch'[s] + ELSE recorder["maxEpoch"]) +RecorderSetRequests(pc) == ("nClientRequest" :> + IF pc[1] = "LeaderProcessRequest" THEN + recorder["nClientRequest"] + 1 + ELSE recorder["nClientRequest"] ) +RecorderSetPc(pc) == ("pc" :> pc) +RecorderSetFailure(pc) == CASE pc[1] = "Timeout" -> RecorderIncTimeout @@ RecorderGetRestart + [] pc[1] = "LeaderTimeout" -> RecorderIncTimeout @@ RecorderGetRestart + [] pc[1] = "FollowerTimeout" -> RecorderIncTimeout @@ RecorderGetRestart + [] pc[1] = "Restart" -> RecorderIncTimeout @@ RecorderIncRestart + [] OTHER -> RecorderGetTimeout @@ RecorderGetRestart + +UpdateRecorder(pc) == recorder' = RecorderSetFailure(pc) @@ RecorderSetTransactionNum(pc) + @@ RecorderSetMaxEpoch(pc) @@ RecorderSetPc(pc) + @@ RecorderSetRequests(pc) @@ recorder +UnchangeRecorder == UNCHANGED recorder + +CheckParameterHelper(n, p, Comp(_,_)) == IF p \in DOMAIN Parameters + THEN Comp(n, Parameters[p]) + ELSE TRUE +CheckParameterLimit(n, p) == CheckParameterHelper(n, p, LAMBDA i, j: i < j) + +CheckTimeout == CheckParameterLimit(recorder.nTimeout, "MaxTimeoutFailures") +CheckTransactionNum == CheckParameterLimit(recorder.nTransaction, "MaxTransactionNum") +CheckEpoch == CheckParameterLimit(recorder.maxEpoch, "MaxEpoch") +CheckRestart == /\ CheckTimeout + /\ CheckParameterLimit(recorder.nRestart, "MaxRestarts") + +CheckStateConstraints == CheckTimeout /\ CheckTransactionNum /\ CheckEpoch /\ CheckRestart +----------------------------------------------------------------------------- +\* Actions about network +PendingCEPOCH(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = CEPOCH +PendingNEWEPOCH(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = NEWEPOCH +PendingACKEPOCH(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = ACKEPOCH +PendingNEWLEADER(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = NEWLEADER +PendingACKLD(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = ACKLD +PendingCOMMITLD(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = COMMITLD +PendingPROPOSE(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = PROPOSE +PendingACK(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = ACK +PendingCOMMIT(i, j) == /\ msgs[j][i] /= << >> + /\ msgs[j][i][1].mtype = COMMIT +\* Add a message to msgs - add a message m to msgs. +Send(i, j, m) == msgs' = [msgs EXCEPT ![i][j] = Append(msgs[i][j], m)] +\* Remove a message from msgs - discard head of msgs. +Discard(i, j) == msgs' = IF msgs[i][j] /= << >> THEN [msgs EXCEPT ![i][j] = Tail(msgs[i][j])] + ELSE msgs +\* Combination of Send and Discard - discard head of msgs[j][i] and add m into msgs. +Reply(i, j, m) == msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]), + ![i][j] = Append(msgs[i][j], m)] +\* Shuffle input buffer. +Clean(i, j) == msgs' = [msgs EXCEPT ![j][i] = << >>, ![i][j] = << >>] +CleanInputBuffer(S) == msgs' = [s \in Server |-> + [v \in Server |-> IF v \in S THEN << >> + ELSE msgs[s][v] ] ] +\* Leader broadcasts a message PROPOSE to all other servers in Q. +\* Note: In paper, Q is fuzzy. We think servers who leader broadcasts NEWLEADER to +\* should receive every PROPOSE. So we consider ackeRecv as Q. +\* Since we let ackeRecv = Q, there may exist some follower receiving COMMIT before +\* COMMITLD, and zxid in COMMIT later than zxid in COMMITLD. To avoid this situation, +\* if f \in ackeRecv but \notin ackldRecv, f should not receive COMMIT until +\* f \in ackldRecv and receives COMMITLD. +Broadcast(i, m) == + LET ackeRecv_quorum == {a \in ackeRecv[i]: a.connected = TRUE } + sid_ackeRecv == { a.sid: a \in ackeRecv_quorum } + IN msgs' = [msgs EXCEPT ![i] = [v \in Server |-> IF /\ v \in sid_ackeRecv + /\ v \in learners[i] + /\ v /= i + THEN Append(msgs[i][v], m) + ELSE msgs[i][v] ] ] +\* Since leader decides to broadcasts message COMMIT when processing ACK, so +\* we need to discard ACK and broadcast COMMIT. +\* Here Q is ackldRecv, because we assume that f should not receive COMMIT until +\* f receives COMMITLD. +DiscardAndBroadcast(i, j, m) == + LET ackldRecv_quorum == {a \in ackldRecv[i]: a.connected = TRUE } + sid_ackldRecv == { a.sid: a \in ackldRecv_quorum } + IN msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]), + ![i] = [v \in Server |-> IF /\ v \in sid_ackldRecv + /\ v \in learners[i] + /\ v /= i + THEN Append(msgs[i][v], m) + ELSE msgs[i][v] ] ] +\* Leader broadcasts LEADERINFO to all other servers in cepochRecv. +DiscardAndBroadcastNEWEPOCH(i, j, m) == + LET new_cepochRecv_quorum == {c \in cepochRecv'[i]: c.connected = TRUE } + new_sid_cepochRecv == { c.sid: c \in new_cepochRecv_quorum } + IN msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]), + ![i] = [v \in Server |-> IF /\ v \in new_sid_cepochRecv + /\ v \in learners[i] + /\ v /= i + THEN Append(msgs[i][v], m) + ELSE msgs[i][v] ] ] +\* Leader broadcasts NEWLEADER to all other servers in ackeRecv. +DiscardAndBroadcastNEWLEADER(i, j, m) == + LET new_ackeRecv_quorum == {a \in ackeRecv'[i]: a.connected = TRUE } + new_sid_ackeRecv == { a.sid: a \in new_ackeRecv_quorum } + IN msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]), + ![i] = [v \in Server |-> IF /\ v \in new_sid_ackeRecv + /\ v \in learners[i] + /\ v /= i + THEN Append(msgs[i][v], m) + ELSE msgs[i][v] ] ] +\* Leader broadcasts COMMITLD to all other servers in ackldRecv. +DiscardAndBroadcastCOMMITLD(i, j, m) == + LET new_ackldRecv_quorum == {a \in ackldRecv'[i]: a.connected = TRUE } + new_sid_ackldRecv == { a.sid: a \in new_ackldRecv_quorum } + IN msgs' = [msgs EXCEPT ![j][i] = Tail(msgs[j][i]), + ![i] = [v \in Server |-> IF /\ v \in new_sid_ackldRecv + /\ v \in learners[i] + /\ v /= i + THEN Append(msgs[i][v], m) + ELSE msgs[i][v] ] ] +----------------------------------------------------------------------------- +\* Define initial values for all variables +InitServerVars == /\ state = [s \in Server |-> LOOKING] + /\ zabState = [s \in Server |-> ELECTION] + /\ acceptedEpoch = [s \in Server |-> 0] + /\ currentEpoch = [s \in Server |-> 0] + /\ history = [s \in Server |-> << >>] + /\ lastCommitted = [s \in Server |-> [ index |-> 0, + zxid |-> <<0, 0>> ] ] + +InitLeaderVars == /\ learners = [s \in Server |-> {}] + /\ cepochRecv = [s \in Server |-> {}] + /\ ackeRecv = [s \in Server |-> {}] + /\ ackldRecv = [s \in Server |-> {}] + /\ sendCounter = [s \in Server |-> 0] + +InitFollowerVars == connectInfo = [s \in Server |-> NullPoint] + +InitElectionVars == leaderOracle = NullPoint + +InitMsgVars == msgs = [s \in Server |-> [v \in Server |-> << >>] ] + +InitVerifyVars == /\ proposalMsgsLog = {} + /\ epochLeader = [i \in 1..MAXEPOCH |-> {} ] + /\ violatedInvariants = [stateInconsistent |-> FALSE, + proposalInconsistent |-> FALSE, + commitInconsistent |-> FALSE, + ackInconsistent |-> FALSE, + messageIllegal |-> FALSE ] + +InitRecorder == recorder = [nTimeout |-> 0, + nTransaction |-> 0, + maxEpoch |-> 0, + nRestart |-> 0, + pc |-> <<"Init">>, + nClientRequest |-> 0] + +Init == /\ InitServerVars + /\ InitLeaderVars + /\ InitFollowerVars + /\ InitElectionVars + /\ InitVerifyVars + /\ InitMsgVars + /\ InitRecorder +----------------------------------------------------------------------------- +\* Utils in state switching +FollowerShutdown(i) == + /\ state' = [state EXCEPT ![i] = LOOKING] + /\ zabState' = [zabState EXCEPT ![i] = ELECTION] + /\ connectInfo' = [connectInfo EXCEPT ![i] = NullPoint] + +LeaderShutdown(i) == + /\ LET S == learners[i] + IN /\ state' = [s \in Server |-> IF s \in S THEN LOOKING ELSE state[s] ] + /\ zabState' = [s \in Server |-> IF s \in S THEN ELECTION ELSE zabState[s] ] + /\ connectInfo' = [s \in Server |-> IF s \in S THEN NullPoint ELSE connectInfo[s] ] + /\ CleanInputBuffer(S) + /\ learners' = [learners EXCEPT ![i] = {}] + +SwitchToFollower(i) == + /\ state' = [state EXCEPT ![i] = FOLLOWING] + /\ zabState' = [zabState EXCEPT ![i] = DISCOVERY] + +SwitchToLeader(i) == + /\ state' = [state EXCEPT ![i] = LEADING] + /\ zabState' = [zabState EXCEPT ![i] = DISCOVERY] + /\ learners' = [learners EXCEPT ![i] = {i}] + /\ cepochRecv' = [cepochRecv EXCEPT ![i] = { [ sid |-> i, + connected |-> TRUE, + epoch |-> acceptedEpoch[i] ] }] + /\ ackeRecv' = [ackeRecv EXCEPT ![i] = { [ sid |-> i, + connected |-> TRUE, + peerLastEpoch |-> currentEpoch[i], + peerHistory |-> history[i] ] }] + /\ ackldRecv' = [ackldRecv EXCEPT ![i] = { [ sid |-> i, + connected |-> TRUE ] }] + /\ sendCounter' = [sendCounter EXCEPT ![i] = 0] + +RemoveCepochRecv(set, sid) == + LET sid_cepochRecv == {s.sid: s \in set} + IN IF sid \notin sid_cepochRecv THEN set + ELSE LET info == CHOOSE s \in set: s.sid = sid + new_info == [ sid |-> sid, + connected |-> FALSE, + epoch |-> info.epoch ] + IN (set \ {info}) \union {new_info} + +RemoveAckeRecv(set, sid) == + LET sid_ackeRecv == {s.sid: s \in set} + IN IF sid \notin sid_ackeRecv THEN set + ELSE LET info == CHOOSE s \in set: s.sid = sid + new_info == [ sid |-> sid, + connected |-> FALSE, + peerLastEpoch |-> info.peerLastEpoch, + peerHistory |-> info.peerHistory ] + IN (set \ {info}) \union {new_info} + +RemoveAckldRecv(set, sid) == + LET sid_ackldRecv == {s.sid: s \in set} + IN IF sid \notin sid_ackldRecv THEN set + ELSE LET info == CHOOSE s \in set: s.sid = sid + new_info == [ sid |-> sid, + connected |-> FALSE ] + IN (set \ {info}) \union {new_info} + +RemoveLearner(i, j) == + /\ learners' = [learners EXCEPT ![i] = @ \ {j}] + /\ cepochRecv' = [cepochRecv EXCEPT ![i] = RemoveCepochRecv(@, j) ] + /\ ackeRecv' = [ackeRecv EXCEPT ![i] = RemoveAckeRecv(@, j) ] + /\ ackldRecv' = [ackldRecv EXCEPT ![i] = RemoveAckldRecv(@, j) ] +----------------------------------------------------------------------------- +\* Actions of election +UpdateLeader(i) == + /\ IsLooking(i) + /\ leaderOracle /= i + /\ leaderOracle' = i + /\ SwitchToLeader(i) + /\ UNCHANGED <> + /\ UpdateRecorder(<<"UpdateLeader", i>>) + +FollowLeader(i) == + /\ IsLooking(i) + /\ leaderOracle /= NullPoint + /\ \/ /\ leaderOracle = i + /\ SwitchToLeader(i) + \/ /\ leaderOracle /= i + /\ SwitchToFollower(i) + /\ UNCHANGED leaderVars + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowLeader", i>>) + +----------------------------------------------------------------------------- +(* Actions of situation error. Situation error in protocol spec is different + from latter specs. This is for compressing state space, we focus on results + from external events (e.g. network partition, node failure, etc.), so we do + not need to add variables and actions about network conditions and node + conditions. It is reasonable that we have action 'Restart' but no 'Crash', + because when a node does not execute any internal events after restarting, + this is equivalent to executing a crash. +*) + +\* Timeout between leader and follower. +Timeout(i, j) == + /\ CheckTimeout \* test restrictions of timeout + /\ IsLeader(i) /\ IsMyLearner(i, j) + /\ IsFollower(j) /\ IsMyLeader(j, i) + /\ LET newLearners == learners[i] \ {j} + IN \/ /\ IsQuorum(newLearners) \* just remove this learner + /\ RemoveLearner(i, j) + /\ FollowerShutdown(j) + /\ Clean(i, j) + \/ /\ ~IsQuorum(newLearners) \* leader switches to looking + /\ LeaderShutdown(i) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"Timeout", i, j>>) + +Restart(i) == + /\ CheckRestart \* test restrictions of restart + /\ \/ /\ IsLooking(i) + /\ UNCHANGED <> + \/ /\ IsFollower(i) + /\ LET connectedWithLeader == HasLeader(i) + IN \/ /\ connectedWithLeader + /\ LET leader == connectInfo[i] + newLearners == learners[leader] \ {i} + IN + \/ /\ IsQuorum(newLearners) \* leader remove learner i + /\ RemoveLearner(leader, i) + /\ FollowerShutdown(i) + /\ Clean(leader, i) + \/ /\ ~IsQuorum(newLearners) \* leader switches to looking + /\ LeaderShutdown(leader) + /\ UNCHANGED <> + \/ /\ ~connectedWithLeader + /\ FollowerShutdown(i) + /\ CleanInputBuffer({i}) + /\ UNCHANGED <> + \/ /\ IsLeader(i) + /\ LeaderShutdown(i) + /\ UNCHANGED <> + /\ lastCommitted' = [lastCommitted EXCEPT ![i] = [ index |-> 0, + zxid |-> <<0, 0>> ] ] + /\ UNCHANGED <> + /\ UpdateRecorder(<<"Restart", i>>) +----------------------------------------------------------------------------- +(* Establish connection between leader and follower. *) +ConnectAndFollowerSendCEPOCH(i, j) == + /\ IsLeader(i) /\ \lnot IsMyLearner(i, j) + /\ IsFollower(j) /\ HasNoLeader(j) /\ leaderOracle = i + /\ learners' = [learners EXCEPT ![i] = @ \union {j}] + /\ connectInfo' = [connectInfo EXCEPT ![j] = i] + /\ Send(j, i, [ mtype |-> CEPOCH, + mepoch |-> acceptedEpoch[j] ]) \* contains f.p + /\ UNCHANGED <> + /\ UpdateRecorder(<<"ConnectAndFollowerSendCEPOCH", i, j>>) + +CepochRecvQuorumFormed(i) == LET sid_cepochRecv == {c.sid: c \in cepochRecv[i]} + IN IsQuorum(sid_cepochRecv) +CepochRecvBecomeQuorum(i) == LET sid_cepochRecv == {c.sid: c \in cepochRecv'[i]} + IN IsQuorum(sid_cepochRecv) + +UpdateCepochRecv(oldSet, sid, peerEpoch) == + LET sid_set == {s.sid: s \in oldSet} + IN IF sid \in sid_set + THEN LET old_info == CHOOSE info \in oldSet: info.sid = sid + new_info == [ sid |-> sid, + connected |-> TRUE, + epoch |-> peerEpoch ] + IN ( oldSet \ {old_info} ) \union {new_info} + ELSE LET follower_info == [ sid |-> sid, + connected |-> TRUE, + epoch |-> peerEpoch ] + IN oldSet \union {follower_info} + +\* Determine new e' in this round from a quorum of CEPOCH. +DetermineNewEpoch(i) == + LET epoch_cepochRecv == {c.epoch: c \in cepochRecv'[i]} + IN Maximum(epoch_cepochRecv) + 1 + +(* Leader waits for receiving FOLLOWERINFO from a quorum including itself, + and chooses a new epoch e' as its own epoch and broadcasts NEWEPOCH. *) +LeaderProcessCEPOCH(i, j) == + /\ CheckEpoch \* test restrictions of max epoch + /\ IsLeader(i) + /\ PendingCEPOCH(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLearner(i, j) + IN /\ infoOk + /\ \/ \* 1. has not broadcast NEWEPOCH + /\ ~CepochRecvQuorumFormed(i) + /\ \/ /\ zabState[i] = DISCOVERY + /\ UNCHANGED violatedInvariants + \/ /\ zabState[i] /= DISCOVERY + /\ PrintT("Exception: CepochRecvQuorumFormed false," \o + " while zabState not DISCOVERY.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.stateInconsistent = TRUE] + /\ cepochRecv' = [cepochRecv EXCEPT ![i] = UpdateCepochRecv(@, j, msg.mepoch) ] + /\ \/ \* 1.1. cepochRecv becomes quorum, + \* then determine e' and broadcasts NEWEPOCH in Q. + /\ CepochRecvBecomeQuorum(i) + /\ acceptedEpoch' = [acceptedEpoch EXCEPT ![i] = DetermineNewEpoch(i)] + /\ LET m == [ mtype |-> NEWEPOCH, + mepoch |-> acceptedEpoch'[i] ] + IN DiscardAndBroadcastNEWEPOCH(i, j, m) + \/ \* 1.2. cepochRecv still not quorum. + /\ ~CepochRecvBecomeQuorum(i) + /\ Discard(j, i) + /\ UNCHANGED acceptedEpoch + \/ \* 2. has broadcast NEWEPOCH + /\ CepochRecvQuorumFormed(i) + /\ cepochRecv' = [cepochRecv EXCEPT ![i] = UpdateCepochRecv(@, j, msg.mepoch) ] + /\ Reply(i, j, [ mtype |-> NEWEPOCH, + mepoch |-> acceptedEpoch[i] ]) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderProcessCEPOCH", i, j>>) + +(* Follower receives LEADERINFO. If newEpoch >= acceptedEpoch, then follower + updates acceptedEpoch and sends ACKEPOCH back, containing currentEpoch and + history. After this, zabState turns to SYNC. *) +FollowerProcessNEWEPOCH(i, j) == + /\ IsFollower(i) + /\ PendingNEWEPOCH(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLeader(i, j) + stateOk == zabState[i] = DISCOVERY + epochOk == msg.mepoch >= acceptedEpoch[i] + IN /\ infoOk + /\ \/ \* 1. Normal case + /\ epochOk + /\ \/ /\ stateOk + /\ acceptedEpoch' = [acceptedEpoch EXCEPT ![i] = msg.mepoch] + /\ LET m == [ mtype |-> ACKEPOCH, + mepoch |-> currentEpoch[i], + mhistory |-> history[i] ] + IN Reply(i, j, m) + /\ zabState' = [zabState EXCEPT ![i] = SYNCHRONIZATION] + /\ UNCHANGED violatedInvariants + \/ /\ ~stateOk + /\ PrintT("Exception: Follower receives NEWEPOCH," \o + " whileZabState not DISCOVERY.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.stateInconsistent = TRUE] + /\ Discard(j, i) + /\ UNCHANGED <> + /\ UNCHANGED <> + \/ \* 2. Abnormal case - go back to election + /\ ~epochOk + /\ FollowerShutdown(i) + /\ LET leader == connectInfo[i] + IN /\ Clean(i, leader) + /\ RemoveLearner(leader, i) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowerProcessNEWEPOCH", i, j>>) + +AckeRecvQuorumFormed(i) == LET sid_ackeRecv == {a.sid: a \in ackeRecv[i]} + IN IsQuorum(sid_ackeRecv) +AckeRecvBecomeQuorum(i) == LET sid_ackeRecv == {a.sid: a \in ackeRecv'[i]} + IN IsQuorum(sid_ackeRecv) + +UpdateAckeRecv(oldSet, sid, peerEpoch, peerHistory) == + LET sid_set == {s.sid: s \in oldSet} + follower_info == [ sid |-> sid, + connected |-> TRUE, + peerLastEpoch |-> peerEpoch, + peerHistory |-> peerHistory ] + IN IF sid \in sid_set + THEN LET old_info == CHOOSE info \in oldSet: info.sid = sid + IN (oldSet \ {old_info}) \union {follower_info} + ELSE oldSet \union {follower_info} + +\* for checking invariants +RECURSIVE SetPacketsForChecking(_,_,_,_,_,_) +SetPacketsForChecking(set, src, ep, his, cur, end) == + IF cur > end THEN set + ELSE LET m_proposal == [ source |-> src, + epoch |-> ep, + zxid |-> his[cur].zxid, + data |-> his[cur].value ] + IN SetPacketsForChecking((set \union {m_proposal}), src, ep, his, cur + 1, end) + + +LastZxidOfHistory(his) == IF Len(his) = 0 THEN <<0, 0>> + ELSE his[Len(his)].zxid + +\* TRUE: f1.a > f2.a or (f1.a = fa.a and f1.zxid >= f2.zxid) +MoreResentOrEqual(ss1, ss2) == \/ ss1.currentEpoch > ss2.currentEpoch + \/ /\ ss1.currentEpoch = ss2.currentEpoch + /\ ~ZxidCompare(ss2.lastZxid, ss1.lastZxid) + +\* Determine initial history Ie' in this round from a quorum of ACKEPOCH. +DetermineInitialHistory(i) == + LET set == ackeRecv'[i] + ss_set == { [ sid |-> a.sid, + currentEpoch |-> a.peerLastEpoch, + lastZxid |-> LastZxidOfHistory(a.peerHistory) ] + : a \in set } + selected == CHOOSE ss \in ss_set: + \A ss1 \in (ss_set \ {ss}): MoreResentOrEqual(ss, ss1) + info == CHOOSE f \in set: f.sid = selected.sid + IN info.peerHistory + +RECURSIVE InitAcksidHelper(_,_) +InitAcksidHelper(txns, src) == IF Len(txns) = 0 THEN << >> + ELSE LET oldTxn == txns[1] + newTxn == [ zxid |-> oldTxn.zxid, + value |-> oldTxn.value, + ackSid |-> {src}, + epoch |-> oldTxn.epoch ] + IN <> \o InitAcksidHelper( Tail(txns), src) + +\* Atomically let all txns in initial history contain self's acks. +InitAcksid(i, his) == InitAcksidHelper(his, i) + +(* Leader waits for receiving ACKEPOPCH from a quorum, and determines initialHistory + according to history of whom has most recent state summary from them. After this, + leader's zabState turns to SYNCHRONIZATION. *) +LeaderProcessACKEPOCH(i, j) == + /\ IsLeader(i) + /\ PendingACKEPOCH(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLearner(i, j) + IN /\ infoOk + /\ \/ \* 1. has broadcast NEWLEADER + /\ AckeRecvQuorumFormed(i) + /\ ackeRecv' = [ackeRecv EXCEPT ![i] = UpdateAckeRecv(@, j, + msg.mepoch, msg.mhistory) ] + /\ LET toSend == history[i] \* contains (Ie', Be') + m == [ mtype |-> NEWLEADER, + mepoch |-> acceptedEpoch[i], + mhistory |-> toSend ] + set_forChecking == SetPacketsForChecking({ }, i, + acceptedEpoch[i], toSend, 1, Len(toSend)) + IN + /\ Reply(i, j, m) + /\ proposalMsgsLog' = proposalMsgsLog \union set_forChecking + /\ UNCHANGED <> + \/ \* 2. has not broadcast NEWLEADER + /\ ~AckeRecvQuorumFormed(i) + /\ \/ /\ zabState[i] = DISCOVERY + /\ UNCHANGED violatedInvariants + \/ /\ zabState[i] /= DISCOVERY + /\ PrintT("Exception: AckeRecvQuorumFormed false," \o + " while zabState not DISCOVERY.") + /\ violatedInvariants' = [violatedInvariants EXCEPT + !.stateInconsistent = TRUE] + /\ ackeRecv' = [ackeRecv EXCEPT ![i] = UpdateAckeRecv(@, j, + msg.mepoch, msg.mhistory) ] + /\ \/ \* 2.1. ackeRecv becomes quorum, determine Ie' + \* and broadcasts NEWLEADER in Q. (l.1.2 + l.2.1) + /\ AckeRecvBecomeQuorum(i) + /\ \* Update f.a + LET newLeaderEpoch == acceptedEpoch[i] IN + /\ currentEpoch' = [currentEpoch EXCEPT ![i] = newLeaderEpoch] + /\ epochLeader' = [epochLeader EXCEPT ![newLeaderEpoch] + = @ \union {i} ] \* for checking invariants + /\ \* Determine initial history Ie' + LET initialHistory == DetermineInitialHistory(i) IN + history' = [history EXCEPT ![i] = InitAcksid(i, initialHistory) ] + /\ \* Update zabState + zabState' = [zabState EXCEPT ![i] = SYNCHRONIZATION] + /\ \* Broadcast NEWLEADER with (e', Ie') + LET toSend == history'[i] + m == [ mtype |-> NEWLEADER, + mepoch |-> acceptedEpoch[i], + mhistory |-> toSend ] + set_forChecking == SetPacketsForChecking({ }, i, + acceptedEpoch[i], toSend, 1, Len(toSend)) + IN + /\ DiscardAndBroadcastNEWLEADER(i, j, m) + /\ proposalMsgsLog' = proposalMsgsLog \union set_forChecking + \/ \* 2.2. ackeRecv still not quorum. + /\ ~AckeRecvBecomeQuorum(i) + /\ Discard(j, i) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderProcessACKEPOCH", i, j>>) +----------------------------------------------------------------------------- +(* Follower receives NEWLEADER. Update f.a and history. *) +FollowerProcessNEWLEADER(i, j) == + /\ IsFollower(i) + /\ PendingNEWLEADER(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLeader(i, j) + epochOk == acceptedEpoch[i] = msg.mepoch + stateOk == zabState[i] = SYNCHRONIZATION + IN /\ infoOk + /\ \/ \* 1. f.p not equals e', starts a new iteration. + /\ ~epochOk + /\ FollowerShutdown(i) + /\ LET leader == connectInfo[i] + IN /\ Clean(i, leader) + /\ RemoveLearner(leader, i) + /\ UNCHANGED <> + \/ \* 2. f.p equals e'. + /\ epochOk + /\ \/ /\ stateOk + /\ UNCHANGED violatedInvariants + \/ /\ ~stateOk + /\ PrintT("Exception: Follower receives NEWLEADER," \o + " whileZabState not SYNCHRONIZATION.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.stateInconsistent = TRUE] + /\ currentEpoch' = [currentEpoch EXCEPT ![i] = acceptedEpoch[i]] + /\ history' = [history EXCEPT ![i] = msg.mhistory] \* no need to care ackSid + /\ LET m == [ mtype |-> ACKLD, + mzxid |-> LastZxidOfHistory(history'[i]) ] + IN Reply(i, j, m) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowerProcessNEWLEADER", i, j>>) + +AckldRecvQuorumFormed(i) == LET sid_ackldRecv == {a.sid: a \in ackldRecv[i]} + IN IsQuorum(sid_ackldRecv) +AckldRecvBecomeQuorum(i) == LET sid_ackldRecv == {a.sid: a \in ackldRecv'[i]} + IN IsQuorum(sid_ackldRecv) + +UpdateAckldRecv(oldSet, sid) == + LET sid_set == {s.sid: s \in oldSet} + follower_info == [ sid |-> sid, + connected |-> TRUE ] + IN IF sid \in sid_set + THEN LET old_info == CHOOSE info \in oldSet: info.sid = sid + IN (oldSet \ {old_info}) \union {follower_info} + ELSE oldSet \union {follower_info} + +LastZxid(i) == LastZxidOfHistory(history[i]) + +RECURSIVE UpdateAcksidHelper(_,_,_) +UpdateAcksidHelper(txns, target, endZxid) == + IF Len(txns) = 0 THEN << >> + ELSE LET oldTxn == txns[1] + IN IF ZxidCompare(oldTxn.zxid, endZxid) THEN txns + ELSE LET newTxn == [ zxid |-> oldTxn.zxid, + value |-> oldTxn.value, + ackSid |-> IF target \in oldTxn.ackSid + THEN oldTxn.ackSid + ELSE oldTxn.ackSid \union {target}, + epoch |-> oldTxn.epoch ] + IN <> \o UpdateAcksidHelper( Tail(txns), target, endZxid) + +\* Atomically add ackSid of one learner according to zxid in ACKLD. +UpdateAcksid(his, target, endZxid) == UpdateAcksidHelper(his, target, endZxid) + +(* Leader waits for receiving ACKLD from a quorum including itself, + and broadcasts COMMITLD and turns to BROADCAST. *) +LeaderProcessACKLD(i, j) == + /\ IsLeader(i) + /\ PendingACKLD(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLearner(i, j) + IN /\ infoOk + /\ \/ \* 1. has not broadcast COMMITLD + /\ ~AckldRecvQuorumFormed(i) + /\ \/ /\ zabState[i] = SYNCHRONIZATION + /\ UNCHANGED violatedInvariants + \/ /\ zabState[i] /= SYNCHRONIZATION + /\ PrintT("Exception: AckldRecvQuorumFormed false," \o + " while zabState not SYNCHRONIZATION.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.stateInconsistent = TRUE] + /\ ackldRecv' = [ackldRecv EXCEPT ![i] = UpdateAckldRecv(@, j) ] + /\ history' = [history EXCEPT ![i] = UpdateAcksid(@, j, msg.mzxid)] + /\ \/ \* 1.1. ackldRecv becomes quorum, + \* then broadcasts COMMITLD and turns to BROADCAST. + /\ AckldRecvBecomeQuorum(i) + /\ lastCommitted' = [lastCommitted EXCEPT + ![i] = [ index |-> Len(history[i]), + zxid |-> LastZxid(i) ] ] + /\ zabState' = [zabState EXCEPT ![i] = BROADCAST] + /\ LET m == [ mtype |-> COMMITLD, + mzxid |-> LastZxid(i) ] + IN DiscardAndBroadcastCOMMITLD(i, j, m) + \/ \* 1.2. ackldRecv still not quorum. + /\ ~AckldRecvBecomeQuorum(i) + /\ Discard(j, i) + /\ UNCHANGED <> + \/ \* 2. has broadcast COMMITLD + /\ AckldRecvQuorumFormed(i) + /\ \/ /\ zabState[i] = BROADCAST + /\ UNCHANGED violatedInvariants + \/ /\ zabState[i] /= BROADCAST + /\ PrintT("Exception: AckldRecvQuorumFormed true," \o + " while zabState not BROADCAST.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.stateInconsistent = TRUE] + /\ ackldRecv' = [ackldRecv EXCEPT ![i] = UpdateAckldRecv(@, j) ] + /\ history' = [history EXCEPT ![i] = UpdateAcksid(@, j, msg.mzxid)] + /\ Reply(i, j, [ mtype |-> COMMITLD, + mzxid |-> lastCommitted[i].zxid ]) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderProcessACKLD", i, j>>) + +RECURSIVE ZxidToIndexHelper(_,_,_,_) +ZxidToIndexHelper(his, zxid, cur, appeared) == + IF cur > Len(his) THEN cur + ELSE IF TxnZxidEqual(his[cur], zxid) + THEN CASE appeared = TRUE -> -1 + [] OTHER -> Minimum( { cur, + ZxidToIndexHelper(his, zxid, cur + 1, TRUE) } ) + ELSE ZxidToIndexHelper(his, zxid, cur + 1, appeared) + +\* return -1: this zxid appears at least twice. Len(his) + 1: does not exist. +\* 1 - Len(his): exists and appears just once. +ZxidToIndex(his, zxid) == IF ZxidEqual( zxid, <<0, 0>> ) THEN 0 + ELSE IF Len(his) = 0 THEN 1 + ELSE LET len == Len(his) IN + IF \E idx \in 1..len: TxnZxidEqual(his[idx], zxid) + THEN ZxidToIndexHelper(his, zxid, 1, FALSE) + ELSE len + 1 + +(* Follower receives COMMITLD. Commit all txns. *) +FollowerProcessCOMMITLD(i, j) == + /\ IsFollower(i) + /\ PendingCOMMITLD(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLeader(i, j) + index == IF ZxidEqual(msg.mzxid, <<0, 0>>) THEN 0 + ELSE ZxidToIndex(history[i], msg.mzxid) + logOk == index >= 0 /\ index <= Len(history[i]) + IN /\ infoOk + /\ \/ /\ logOk + /\ UNCHANGED violatedInvariants + \/ /\ ~logOk + /\ PrintT("Exception: zxid in COMMITLD not exists in history.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.proposalInconsistent = TRUE] + /\ lastCommitted' = [lastCommitted EXCEPT ![i] = [ index |-> index, + zxid |-> msg.mzxid ] ] + /\ zabState' = [zabState EXCEPT ![i] = BROADCAST] + /\ Discard(j, i) + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowerProcessCOMMITLD", i, j>>) +---------------------------------------------------------------------------- +IncZxid(s, zxid) == IF currentEpoch[s] = zxid[1] THEN <> + ELSE <> + +(* Leader receives client request. + Note: In production, any server in traffic can receive requests and + forward it to leader if necessary. We choose to let leader be + the sole one who can receive write requests, to simplify spec + and keep correctness at the same time. *) +LeaderProcessRequest(i) == + /\ CheckTransactionNum \* test restrictions of transaction num + /\ IsLeader(i) + /\ zabState[i] = BROADCAST + /\ LET request_value == GetRecorder("nClientRequest") \* unique value + newTxn == [ zxid |-> IncZxid(i, LastZxid(i)), + value |-> request_value, + ackSid |-> {i}, + epoch |-> currentEpoch[i] ] + IN history' = [history EXCEPT ![i] = Append(@, newTxn) ] + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderProcessRequest", i>>) + +\* Latest counter existing in history. +CurrentCounter(i) == IF LastZxid(i)[1] = currentEpoch[i] THEN LastZxid(i)[2] + ELSE 0 + +(* Leader broadcasts PROPOSE when sendCounter < currentCounter. *) +LeaderBroadcastPROPOSE(i) == + /\ IsLeader(i) + /\ zabState[i] = BROADCAST + /\ sendCounter[i] < CurrentCounter(i) \* there exists proposal to be sent + /\ LET toSendCounter == sendCounter[i] + 1 + toSendZxid == <> + toSendIndex == ZxidToIndex(history[i], toSendZxid) + toSendTxn == history[i][toSendIndex] + m_proposal == [ mtype |-> PROPOSE, + mzxid |-> toSendTxn.zxid, + mdata |-> toSendTxn.value ] + m_proposal_forChecking == [ source |-> i, + epoch |-> currentEpoch[i], + zxid |-> toSendTxn.zxid, + data |-> toSendTxn.value ] + IN /\ sendCounter' = [sendCounter EXCEPT ![i] = toSendCounter] + /\ Broadcast(i, m_proposal) + /\ proposalMsgsLog' = proposalMsgsLog \union {m_proposal_forChecking} + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderBroadcastPROPOSE", i>>) + +IsNextZxid(curZxid, nextZxid) == + \/ \* first PROPOSAL in this epoch + /\ nextZxid[2] = 1 + /\ curZxid[1] < nextZxid[1] + \/ \* not first PROPOSAL in this epoch + /\ nextZxid[2] > 1 + /\ curZxid[1] = nextZxid[1] + /\ curZxid[2] + 1 = nextZxid[2] + +(* Follower processes PROPOSE, saves it in history and replies ACK. *) +FollowerProcessPROPOSE(i, j) == + /\ IsFollower(i) + /\ PendingPROPOSE(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLeader(i, j) + isNext == IsNextZxid(LastZxid(i), msg.mzxid) + newTxn == [ zxid |-> msg.mzxid, + value |-> msg.mdata, + ackSid |-> {}, + epoch |-> currentEpoch[i] ] + m_ack == [ mtype |-> ACK, + mzxid |-> msg.mzxid ] + IN /\ infoOk + /\ \/ /\ isNext + /\ history' = [history EXCEPT ![i] = Append(@, newTxn)] + /\ Reply(i, j, m_ack) + /\ UNCHANGED violatedInvariants + \/ /\ ~isNext + /\ LET index == ZxidToIndex(history[i], msg.mzxid) + exist == index > 0 /\ index <= Len(history[i]) + IN \/ /\ exist + /\ UNCHANGED violatedInvariants + \/ /\ ~exist + /\ PrintT("Exception: Follower receives PROPOSE, while" \o + " txn is neither the next nor exists in history.") + /\ violatedInvariants' = [violatedInvariants EXCEPT + !.proposalInconsistent = TRUE] + /\ Discard(j, i) + /\ UNCHANGED history + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowerProcessPROPOSE", i, j>>) + +LeaderTryToCommit(s, index, zxid, newTxn, follower) == + LET allTxnsBeforeCommitted == lastCommitted[s].index >= index - 1 + \* Only when all proposals before zxid has been committed, + \* this proposal can be permitted to be committed. + hasAllQuorums == IsQuorum(newTxn.ackSid) + \* In order to be committed, a proposal must be accepted + \* by a quorum. + ordered == lastCommitted[s].index + 1 = index + \* Commit proposals in order. + IN \/ /\ \* Current conditions do not satisfy committing the proposal. + \/ ~allTxnsBeforeCommitted + \/ ~hasAllQuorums + /\ Discard(follower, s) + /\ UNCHANGED <> + \/ /\ allTxnsBeforeCommitted + /\ hasAllQuorums + /\ \/ /\ ~ordered + /\ PrintT("Warn: Committing zxid " \o ToString(zxid) \o " not first.") + /\ violatedInvariants' = [violatedInvariants EXCEPT + !.commitInconsistent = TRUE] + \/ /\ ordered + /\ UNCHANGED violatedInvariants + /\ lastCommitted' = [lastCommitted EXCEPT ![s] = [ index |-> index, + zxid |-> zxid ] ] + /\ LET m_commit == [ mtype |-> COMMIT, + mzxid |-> zxid ] + IN DiscardAndBroadcast(s, follower, m_commit) + + +LastAckIndexFromFollower(i, j) == + LET set_index == {idx \in 1..Len(history[i]): j \in history[i][idx].ackSid } + IN Maximum(set_index) + +(* Leader Keeps a count of acks for a particular proposal, and try to + commit the proposal. If committed, COMMIT of proposal will be broadcast. *) +LeaderProcessACK(i, j) == + /\ IsLeader(i) + /\ PendingACK(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLearner(i, j) + index == ZxidToIndex(history[i], msg.mzxid) + exist == index >= 1 /\ index <= Len(history[i]) \* proposal exists in history + outstanding == lastCommitted[i].index < Len(history[i]) \* outstanding not null + hasCommitted == ~ZxidCompare(msg.mzxid, lastCommitted[i].zxid) + ackIndex == LastAckIndexFromFollower(i, j) + monotonicallyInc == \/ ackIndex = -1 + \/ ackIndex + 1 = index + IN /\ infoOk + /\ \/ /\ exist + /\ monotonicallyInc + /\ LET txn == history[i][index] + txnAfterAddAck == [ zxid |-> txn.zxid, + value |-> txn.value, + ackSid |-> txn.ackSid \union {j} , + epoch |-> txn.epoch ] + IN + /\ history' = [history EXCEPT ![i][index] = txnAfterAddAck ] + /\ \/ /\ \* Note: outstanding is 0. + \* / proposal has already been committed. + \/ ~outstanding + \/ hasCommitted + /\ Discard(j, i) + /\ UNCHANGED <> + \/ /\ outstanding + /\ ~hasCommitted + /\ LeaderTryToCommit(i, index, msg.mzxid, txnAfterAddAck, j) + \/ /\ \/ ~exist + \/ ~monotonicallyInc + /\ PrintT("Exception: No such zxid. " \o + " / ackIndex doesn't inc monotonically.") + /\ violatedInvariants' = [violatedInvariants + EXCEPT !.ackInconsistent = TRUE] + /\ Discard(j, i) + /\ UNCHANGED <> + /\ UNCHANGED <> + /\ UpdateRecorder(<<"LeaderProcessACK", i, j>>) + +(* Follower processes COMMIT. *) +FollowerProcessCOMMIT(i, j) == + /\ IsFollower(i) + /\ PendingCOMMIT(i, j) + /\ LET msg == msgs[j][i][1] + infoOk == IsMyLeader(i, j) + pending == lastCommitted[i].index < Len(history[i]) + IN /\ infoOk + /\ \/ /\ ~pending + /\ PrintT("Warn: Committing zxid without seeing txn.") + /\ UNCHANGED <> + \/ /\ pending + /\ LET firstElement == history[i][lastCommitted[i].index + 1] + match == ZxidEqual(firstElement.zxid, msg.mzxid) + IN + \/ /\ ~match + /\ PrintT("Exception: Committing zxid not equals" \o + " next pending txn zxid.") + /\ violatedInvariants' = [violatedInvariants EXCEPT + !.commitInconsistent = TRUE] + /\ UNCHANGED lastCommitted + \/ /\ match + /\ lastCommitted' = [lastCommitted EXCEPT ![i] = + [ index |-> lastCommitted[i].index + 1, + zxid |-> firstElement.zxid ] ] + /\ UNCHANGED violatedInvariants + /\ Discard(j, i) + /\ UNCHANGED <> + /\ UpdateRecorder(<<"FollowerProcessCOMMIT", i, j>>) +---------------------------------------------------------------------------- +(* Used to discard some messages which should not exist in network channel. + This action should not be triggered. *) +FilterNonexistentMessage(i) == + /\ \E j \in Server \ {i}: /\ msgs[j][i] /= << >> + /\ LET msg == msgs[j][i][1] + IN + \/ /\ IsLeader(i) + /\ LET infoOk == IsMyLearner(i, j) + IN + \/ msg.mtype = NEWEPOCH + \/ msg.mtype = NEWLEADER + \/ msg.mtype = COMMITLD + \/ msg.mtype = PROPOSE + \/ msg.mtype = COMMIT + \/ /\ ~infoOk + /\ \/ msg.mtype = CEPOCH + \/ msg.mtype = ACKEPOCH + \/ msg.mtype = ACKLD + \/ msg.mtype = ACK + \/ /\ IsFollower(i) + /\ LET infoOk == IsMyLeader(i, j) + IN + \/ msg.mtype = CEPOCH + \/ msg.mtype = ACKEPOCH + \/ msg.mtype = ACKLD + \/ msg.mtype = ACK + \/ /\ ~infoOk + /\ \/ msg.mtype = NEWEPOCH + \/ msg.mtype = NEWLEADER + \/ msg.mtype = COMMITLD + \/ msg.mtype = PROPOSE + \/ msg.mtype = COMMIT + \/ IsLooking(i) + /\ Discard(j, i) + /\ violatedInvariants' = [violatedInvariants EXCEPT !.messageIllegal = TRUE] + /\ UNCHANGED <> + /\ UnchangeRecorder +---------------------------------------------------------------------------- +\* Defines how the variables may transition. +Next == + (* Election *) + \/ \E i \in Server: UpdateLeader(i) + \/ \E i \in Server: FollowLeader(i) + (* Abnormal situations like failure, network disconnection *) + \/ \E i, j \in Server: Timeout(i, j) + \/ \E i \in Server: Restart(i) + (* Zab module - Discovery and Synchronization part *) + \/ \E i, j \in Server: ConnectAndFollowerSendCEPOCH(i, j) + \/ \E i, j \in Server: LeaderProcessCEPOCH(i, j) + \/ \E i, j \in Server: FollowerProcessNEWEPOCH(i, j) + \/ \E i, j \in Server: LeaderProcessACKEPOCH(i, j) + \/ \E i, j \in Server: FollowerProcessNEWLEADER(i, j) + \/ \E i, j \in Server: LeaderProcessACKLD(i, j) + \/ \E i, j \in Server: FollowerProcessCOMMITLD(i, j) + (* Zab module - Broadcast part *) + \/ \E i \in Server: LeaderProcessRequest(i) + \/ \E i \in Server: LeaderBroadcastPROPOSE(i) + \/ \E i, j \in Server: FollowerProcessPROPOSE(i, j) + \/ \E i, j \in Server: LeaderProcessACK(i, j) + \/ \E i, j \in Server: FollowerProcessCOMMIT(i, j) + (* An action used to judge whether there are redundant messages in network *) + \/ \E i \in Server: FilterNonexistentMessage(i) + +Spec == Init /\ [][Next]_vars +---------------------------------------------------------------------------- +\* Define safety properties of Zab. + +ShouldNotBeTriggered == \A p \in DOMAIN violatedInvariants: violatedInvariants[p] = FALSE + +\* There is most one established leader for a certain epoch. +Leadership1 == \A i, j \in Server: + /\ IsLeader(i) /\ zabState[i] \in {SYNCHRONIZATION, BROADCAST} + /\ IsLeader(j) /\ zabState[j] \in {SYNCHRONIZATION, BROADCAST} + /\ currentEpoch[i] = currentEpoch[j] + => i = j + +Leadership2 == \A epoch \in 1..MAXEPOCH: Cardinality(epochLeader[epoch]) <= 1 + +\* PrefixConsistency: The prefix that have been committed +\* in history in any process is the same. +PrefixConsistency == \A i, j \in Server: + LET smaller == Minimum({lastCommitted[i].index, lastCommitted[j].index}) + IN \/ smaller = 0 + \/ /\ smaller > 0 + /\ \A index \in 1..smaller: + TxnEqual(history[i][index], history[j][index]) + +\* Integrity: If some follower delivers one transaction, then some primary has broadcast it. +Integrity == \A i \in Server: + /\ IsFollower(i) + /\ lastCommitted[i].index > 0 + => \A idx \in 1..lastCommitted[i].index: \E proposal \in proposalMsgsLog: + LET txn_proposal == [ zxid |-> proposal.zxid, + value |-> proposal.data ] + IN TxnEqual(history[i][idx], txn_proposal) + +\* Agreement: If some follower f delivers transaction a and some follower f' delivers transaction b, +\* then f' delivers a or f delivers b. +Agreement == \A i, j \in Server: + /\ IsFollower(i) /\ lastCommitted[i].index > 0 + /\ IsFollower(j) /\ lastCommitted[j].index > 0 + => + \A idx1 \in 1..lastCommitted[i].index, idx2 \in 1..lastCommitted[j].index : + \/ \E idx_j \in 1..lastCommitted[j].index: + TxnEqual(history[j][idx_j], history[i][idx1]) + \/ \E idx_i \in 1..lastCommitted[i].index: + TxnEqual(history[i][idx_i], history[j][idx2]) + +\* Total order: If some follower delivers a before b, then any process that delivers b +\* must also deliver a and deliver a before b. +TotalOrder == \A i, j \in Server: + LET committed1 == lastCommitted[i].index + committed2 == lastCommitted[j].index + IN committed1 >= 2 /\ committed2 >= 2 + => \A idx_i1 \in 1..(committed1 - 1) : \A idx_i2 \in (idx_i1 + 1)..committed1 : + LET logOk == \E idx \in 1..committed2 : + TxnEqual(history[i][idx_i2], history[j][idx]) + IN \/ ~logOk + \/ /\ logOk + /\ \E idx_j2 \in 1..committed2 : + /\ TxnEqual(history[i][idx_i2], history[j][idx_j2]) + /\ \E idx_j1 \in 1..(idx_j2 - 1): + TxnEqual(history[i][idx_i1], history[j][idx_j1]) + +\* Local primary order: If a primary broadcasts a before it broadcasts b, then a follower that +\* delivers b must also deliver a before b. +LocalPrimaryOrder == LET p_set(i, e) == {p \in proposalMsgsLog: /\ p.source = i + /\ p.epoch = e } + txn_set(i, e) == { [ zxid |-> p.zxid, + value |-> p.data ] : p \in p_set(i, e) } + IN \A i \in Server: \A e \in 1..currentEpoch[i]: + \/ Cardinality(txn_set(i, e)) < 2 + \/ /\ Cardinality(txn_set(i, e)) >= 2 + /\ \E txn1, txn2 \in txn_set(i, e): + \/ TxnEqual(txn1, txn2) + \/ /\ ~TxnEqual(txn1, txn2) + /\ LET TxnPre == IF ZxidCompare(txn1.zxid, txn2.zxid) THEN txn2 ELSE txn1 + TxnNext == IF ZxidCompare(txn1.zxid, txn2.zxid) THEN txn1 ELSE txn2 + IN \A j \in Server: /\ lastCommitted[j].index >= 2 + /\ \E idx \in 1..lastCommitted[j].index: + TxnEqual(history[j][idx], TxnNext) + => \E idx2 \in 1..lastCommitted[j].index: + /\ TxnEqual(history[j][idx2], TxnNext) + /\ idx2 > 1 + /\ \E idx1 \in 1..(idx2 - 1): + TxnEqual(history[j][idx1], TxnPre) + +\* Global primary order: A follower f delivers both a with epoch e and b with epoch e', and e < e', +\* then f must deliver a before b. +GlobalPrimaryOrder == \A i \in Server: lastCommitted[i].index >= 2 + => \A idx1, idx2 \in 1..lastCommitted[i].index: + \/ ~EpochPrecedeInTxn(history[i][idx1], history[i][idx2]) + \/ /\ EpochPrecedeInTxn(history[i][idx1], history[i][idx2]) + /\ idx1 < idx2 + +\* Primary integrity: If primary p broadcasts a and some follower f delivers b such that b has epoch +\* smaller than epoch of p, then p must deliver b before it broadcasts a. +PrimaryIntegrity == \A i, j \in Server: /\ IsLeader(i) /\ IsMyLearner(i, j) + /\ IsFollower(j) /\ IsMyLeader(j, i) + /\ zabState[i] = BROADCAST + /\ zabState[j] = BROADCAST + /\ lastCommitted[j].index >= 1 + => \A idx_j \in 1..lastCommitted[j].index: + \/ history[j][idx_j].zxid[1] >= currentEpoch[i] + \/ /\ history[j][idx_j].zxid[1] < currentEpoch[i] + /\ \E idx_i \in 1..lastCommitted[i].index: + TxnEqual(history[i][idx_i], history[j][idx_j]) +============================================================================= +\* Modification History +\* Last modified Tue Jan 31 20:40:11 CST 2023 by huangbinyu +\* Last modified Sat Dec 11 22:31:08 CST 2021 by Dell +\* Created Thu Dec 02 20:49:23 CST 2021 by Dell diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/doc.md b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/doc.md new file mode 100644 index 0000000000000000000000000000000000000000..f4bb09b3494b19f80c491b59d7d6b4bb78f53824 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/doc.md @@ -0,0 +1,120 @@ + + +# ZooKeeper's Protocol Specification of TLA+ + +## Overview +ZooKeeper's Protocol Specification focuses on the Zookeeper Atomic Broadcast (Zab) consensus protocol proposed in *Junqueira F P, Reed B C, Serafini M. Zab: High-performance broadcast for primary-backup systems[C]//2011 IEEE/IFIP 41st International Conference on Dependable Systems & Networks (DSN). IEEE, 2011: 245-256*. + +We have completed the the [protocol specification](Zab.tla) for Zab using TLA+ toolbox, and we have done a certain scale of model checking to verify the correctness of Zab. From the experience, we have found some subtle [issues](issues.md) related to the protocol specification and the Zab informal description. + +To handle the ambiguities and omissions of the informal description in the paper, we supplement the specification with some further details. If you have any question, please let us know. + + + +## Specification Development + + +### Requirements +TLA+ toolbox version 1.7.0 + +### Run +Create specification [Zab.tla](Zab.tla) and run models in the following way. +We can clearly divide spec into five modules, which are: + +- Phase0. Leader Election +- Phase1. Discovery +- Phase2. Synchronization +- Phase3. Broadcast +- Abnormal situations like failure, network disconnection + +#### Assign constants +After creating this new model and choosing *Temporal formula* with value *Spec*, we first assign most of constants. +We should set CONSTANTS about server states as model value, including *FOLLOWING*, *LEADING*, and *LOOKING*. +We should set CONSTANTS about server zabStates as model value, including *ELECTION*, *DISCOVERY*, *SYNCHRONIZATION*, and *BROADCAST*. +We should set CONSTANTS about message types as model value, including *CEPOCH*, *NEWEPOCH*, *ACKE*, *NEWLEADER*, *ACKLD*, *COMMITLD*, *PROPOSE*, *ACK*, and *COMMIT*. + +#### Assign left constants affecting state space +Then we should assign CONSTANTS *Server* as a symmetrical model value(such as {s1, s2, s3}). +To compress state space, we need to assign CONSTANT *Parameters* as a record, whose domain contains *MaxTimeoutFailures*, *MaxTransactionNum*, *MaxEpoch*, and *MaxRestarts*. For example, we can assign it to format like [MaxTimeoutFailures |-> 3, MaxTransactionNum |-> 5, MaxEpoch |-> 3, MaxRestarts |-> 2]. + +#### Assign invariants +We remove *'Deadlock'* option. +We add invariants defined in spec into *'Invariants'* to check whether the model will reach an illogical state, including *ShouldNotBeTriggered*, *Leadership1*, *Leadership2*, *PrefixConsistency*, *Integrity*, *Agreement*, *TotalOrder*, *LocalPrimaryOrder*, *GlobalPriamryOrder*, and *PrimaryIntegrity*. +Here the meanings of these invariants are described in the following. Except for the first four, all invariants are defined in paper. + - **ShouldNotBeTriggered**: Some conditions should not be triggered when we are running the model. For example, follower should not receive NEWLEADER when its zabState is not SYNCHRONIZATION. + - **Lerdership**: There is most one established leader in a certain epoch.(Established means leader has updated its f.a and switched its zabState to SYNCHRONIZATION.) + - **PrefixConsistency**: Transactions that have been committed in history are the same in any server. + - **Integrity**: If some follower delivers one transaction, some primary must have broadcast it. + - **Agreement**: If some follower *f1* delivers transaction *a* and some follower *f2* delivers transaction *b*, then *f2* delivers *a* or *f1* delivers *b*. + - **TotalOrder**: If some server delivers *a* before *b*, then any server that delivers *b* must also deliver *a* and deliver *a* before *b*. + - **LocalPrimaryOrder**: If a primary broadcasts *a* before it broadcasts *b*, then a follower that delivers *b* must also deliver *a* before *b*. + - **GlobalPrimaryOrder**: A server *f* delivers both *a* with epoch *e* and *b* with epoch *e'*, and *e* < *e'*, then *f* must deliver *a* before *b*. + - **PrimaryIntegrity**: If primary *p* broadcasts *a* and some follower *f* delivers *b* such that *b* has epoch smaller than epoch of *p*, then *p* must deliver *b* before it broadcasts *a*. + +#### Assign additional TLC options +We set number of worker threads as 10(if unavailable on your system, just decrease it). +We can choose checking mode from *Model-checking mode* and *simulation mode*. + +- Model-checking mode: It is a traverse method like BFS. Diameter in results represent the maximum depth when traversing. All intermediate results will be saved as binary files locally and occupy a large space if running time is long. +- Simulation mode: Everytime TLC randomly chooses a path and run through it until reaching termination or reaching maximum length of the trace, and randomly chooses another path. Currently we set *Maximum length of the trace* as 100. +Here we mainly use simulation mode to discover if there exists deep bugs, which is hard to be found in model-checking mode. + + + +### Results + +You can find our [result](verification-statistics.md) of verification using TLC model checking. + +## Adjustments in protocol spec from paper +>Because the pursuit of the paper is to describe the Zab protocol to others in a concise manner, which will lead to insufficient description of the protocol, there are missing or vague places in the paper. As a mathematical language, no ambiguity is allowed in the TLA+ specification, and this is why we need adjustment. + +Overall, we categorize the flaws of the original paper into two classes: abstraction and vagueness. + +### Abstraction + +There is a missing part in the paper, in which the pseudocode uses the **Discovery** stage as the initial stage of each round, and omits the **Election** stage. + +On the one hand, in spec, **Election** helps advance the state of the system, and is also related to the liveness and strong consistency of the system, so we cannot omit it. On the other hand, our focus is on Zab, so the **Election** module should be expressed with a small number of variables and actions to reduce the state space of the model. + +We use one variable *leaderOracle* and two actions *UpdateLeader* and *FollowerLeader* to express the **election** module streamlined. + +### Vagueness + +We categorize vagueness in the paper into two classes: vagueness in variables and vagueness in actions. + +#### Vagueness in variables +First, the character **Q** is used everywhere in the pseudocode to represent the set of Followers perceived by the Leader in the current term. We divide the set **Q** specifically into variables *learners*, *cepochRecv*, *ackeRecv* and *ackldRecv*. We use *cepochRecv* to let Leader broadcast *NEWEPOCH*, *ackeRecv* to let Leader broadcast *NEWLEADER* and *PROPOSE*, *ackldRecv* to let Leader broadcast *COMMIT-LD* and *COMMIT*. We will explain the reason why we use these sets when Leader broadcasts *PROPOSE* and *COMMIT* in the [issues](issues.md). + +Second, *zxid* in *COMMIT-LD* is omitted in hte paper. We will explain the value of the *zxid* in the [issues](issues.md). + +#### Vagueness in actions +Totally, adjustment on vagueness in actions can be divided into two classes: Completing the missing description and Adjusting the protocol structure. + +* For completing the missing description, we categorize four classes: + + 1. Complete the branch of action where after the Leader node processes the message *m* of type *t*, the receiving set of messages of type *t* still does not satisfy the quorum. + 2. Complete the branch of action where before the Leader node processes the message *m* of type *t*, the receiving set of messages of type *t* has already satisfied the quorum. + 3. Supplement the logical action that the Leader receives the request from the client, encapsulates the request as a log entry, and persists the log entry. + 4. Supplement the logical action that the Leader tries to commit log entries based on confirmation information from followers. + +* For adjusting the protocol structure, in order to improve the readability of the spec, we impose standardized and unified restrictions on the spec. That is, the division unit is to one node receiving and processing one message. Each action, except actions in election module and environment error module, makes a node receiving a certain message a trigger condition, and then produces a subsequent state change. + +See example when Leader processes message *CEPOCH* from one follower: + +![case_leader_process_cepoch](pic/case_leader_process_cepoch.png) diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/issues.md b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/issues.md new file mode 100644 index 0000000000000000000000000000000000000000..c6d2bcd857ff846de6f69df0018906072ab1b1f5 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/issues.md @@ -0,0 +1,58 @@ + + +# Issues + +>This document describes issues related to the ambiguous description of the Zab protocol. + +## (Issue 1)Issue introduced by vague explanation of broadcast object set Q +Because the Leader will only accept the client request when it reaches the *Broadcast* stage, thus when Leader broadcasting messages from *Broadcast* stage, we naturally use the set *ackldRecv* as the object set when Leader broadcasting *Propose* and *Commit* messages in the initial protocol. + +On this basis, the model checking found that there was an error in the protocol. After analyzing the execution path and the violated invariant, we located the error in the action *FollowerProcessCommit*. The Follower received an illegal *COMMIT* message, as shown in the figure below. In the *COMMIT* message, the log entry corresponding to the *zxid* does not exist in the local log. + +![protocol-spec-mck-bug1](pic/protocol-spec-mck-bug1.png) + +A quorum of nodes including node *A* and node *B* completed the log recovery, and entered the *Broadcast* stage. Leader node *B* sent *NEWLEADER*(1, <[1, 1, v1]>) to node *C*, which joined the cluster. Then Leader *B* received client request and broadcast *PROPOSE*([1, 2, v2]). But node *C* did not receive the message because *C* is not in *B*'s *ackldRecv*. Later, the Leader firstly processes *ACK-LD* from *C* and then *ACK* from *A*. So, the object of Leader *B*'s broadcast *COMMIT*([1, 2]) contains *C*, and there is no log entry with *zxid* [1, 2] locally in *C*. + +We found that because the set of objects when the Leader broadcast *PROPOSE* is *ackldRecv*, the Follower will not receive messages with type *PROPOSE* until receiving the *COMMIT-LD*. If a log entry is committed between the Leader sending *NEWLEADER* and *COMMIT-LD*, the corresponding receiver will permanently lose the log entry. + +Therefore, we have made amendments in the spec. When the Leader broadcasts *PROPOSE*, the set of sending objects has been changed from *ackldRecv* to *ackeRecv*. We successfully discovered errors introduced by the vague description of **Q** in the protocol through model checking, and fixed them in the specification. + +## (Issue 2) Issue introduced by lack of client request logic +Since there is no descriptions about client request, we need to add a process that describes the Leader receives a client request and encapsulates the request as a new log entry and appends it to the local log. This process are represented as action *LeaderProcessRequest* in the spec. + +In our original specification, when Follower receives the message *PROPOSE*, the *zxid* of the proposed log entry should be the successor *zxid* of the latest local log entry‘s *zxid*, otherwise it will be regarded as an illegal *PROPOSE*. + +On this basis, model checking told us that there was an error in the model, as shown in the figure below, where Follower receives redundant *PROPOSE* from the same log entry. + +![protocol-spec-mck-bug2](pic/protocol-spec-mck-bug2.png) + +A quorum of nodes including node *A* and *B* completed log recovery first and entered the *Broadcast* stage. When receiving a client request, Leader B encapsulated the request as a log entry [1, 1, v1]. Before B broadcast the proposal of the log entry, node *C* that joined the cluster later sent *ACKEPOCH* to *B*, and *B* replied with *NEWLEADER*(1, <[1, 1, v1]>), and added *C* to the set *ackeRecv*. So the *PROPOSE*([1, 1, v1]) broadcast by *B* was also sent to *C*, so *C* received the redundant proposal for the log entry [1, 1, v1]. + +We have analyzed two repair schemes. The first scheme is to atomize the actions *LeaderProcessRequest* and *LeaderBroadcastPROPOSE* and merge them into one action. The second scheme is to relax the constraints, where if the Follower receives redundant *PROPOSE*, it will be release this message directly. We chose the second scheme, because we think the situation is not serious and will not affect the correctness of Zab. + +## (Issue 3) Issue introduced by ambiguity of zxid in the message COMMIT-LD +When the Leader sends *COMMIT-LD*, the paper does not express the specific value of the *zxid* carried in the message. Therefore, we naturally set the *zxid* carried in *COMMIT-LD* to the *zxid* in *ACK-LD*. + +Therefore, the model checking found an invariant violation, as shown in the figure below, the Follower received an illegal message *COMMIT*. + +![protocol-spec-mck-bug3](pic/protocol-spec-mck-bug3.png) + +A quorum of nodes including node *A* and *B* completed log recovery first and entered the *Broadcast* stage. When the node *C* that joined the cluster later sent *ACKEPOCH* to Leader *B*, *B* sent *NEWLEADER*(1, <[1, 1, v1]>) to *C*, and then received the client request to broadcast *PROPOSE*([1, 2, v2]). Then, *B* received the message *ACK*([1, 2]) from *A* before receiving *ACK-LD* from *C*, so Leader *B* committed the log entry [1, 2, v2] and broadcasts *COMMIT*([1, 2]). Because the object set when broadcasting *COMMIT* is *ackldRecv*, *C* did not receive the commit message. Afterwards, *B* processed the *ACK-LD*([1, 1]) from *C*, and replied with *COMMIT-LD*([1, 1]). Therefore, when Leader *B* reached a consensus on the new log entry [1, 3, v3], it sendt *COMMIT*([1, 3]) to *C*, and *C* found that entry [1, 2, v2] in the local log has not been committed yet, which was treated as an illegal *COMMIT*. + +The repair solution we analyzed is that in the action *LeaderProcessACKLD*, the *zxid* carried by *COMMIT-LD* is changed from the *zxid* in *ACK-LD* to the latest *zxid* committed locally by Leader, thus making up for the missing commit information. diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/verification-statistics.md b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/verification-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..df7d0f1b9bd723cb0d2b35b6418fa6b17ffc98fe --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/protocol-spec/verification-statistics.md @@ -0,0 +1,62 @@ + + +# Verification Statistics +##### Experiment configuration + +Our statistical results include: diameter of the system states that have been traversed, the number of states that have been traversed, the number of different states that have been discovered, and the time spent in the experiment. + +The machine configuration used in the experiment is 2.40 GHz, 10-core CPU, 64GB memory. The TLC version number is 1.7.0. + + + +##### State space constraints in model checking + +Due to the state space explosion in model checking and the complex actions of Zab protocol, as well as unlimited number of rounds and unlimited length of history, it is impossible to traverse all states. +We try to let models can tap into larger state space. See CONSTANT *Parameters* for details. + + + +##### Verification statistics of model checking +| Mode | TLC model | Diameter | num of states | time of checking(hh:mm:ss) | +| ----- | ---------------------- | ------------- | ------------------ | ------------------ | +| BFS | (2 servers,3 rounds,2 transactions) | 59 | 7758091583 | 17:28:17| +| Simulation | (2 servers,3 rounds,2 transactions) | -| 6412825222| 17:07:20 | +| BFS | (3 servers,2 rounds,2 transactions) | 19 | 4275801206 | 09:40:08| +| Simulation | (3 servers,2 rounds,2 transactions) | -| 10899460942| 20:15:11 | +| BFS | (3 servers,2 rounds,3 transactions) | 22 | 8740566213 | 17:49:09 | +| Simulation | (3 servers,2 rounds,3 transactions) | - | 9639135842 | 20:10:00 | +| BFS | (3 servers,3 rounds,2 transactions) | 21 | 7079744342 |14:17:45 | +| Simulation | (3 servers,3 rounds,2 transactions) | - | 6254964039 | 15:08:42 | +| BFS | (4 servers,3 rounds,2 transactions) | 16 | 5634112480 |15:42:09 | +| Simulation | (4 servers,3 rounds,2 transactions) | - | 3883461291 | 15:52:03 | + + + +##### Verification statistics with parameters (count of servers, MaxTotalRestartNum, MaxElectionNum, MaxTransactionNum) + +| Mode | TLC model | Diameter | num of states | time of checking(hh:mm:ss) | +| ----- | ---------------------- | ------------- | ------------------ | ------------------ | +| BFS | (2,2,3,2,termination) | 55 | 10772649 | 00:02:21| +| BFS | (3,1,1,2) | 45 | 9602018536 | 31:01:57| + + + +##### Issues + +Besides, we have found several issues related to the ambiguous description of the Zab protocol. Details can be found at [issues.md](issues.md). diff --git a/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/system-spec/doc.md b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/system-spec/doc.md new file mode 100644 index 0000000000000000000000000000000000000000..1a7d33b72a1ad22efca702ea9edf8363513495d4 --- /dev/null +++ b/local-test-zookeeper-delta-01/afc-zookeeper/zookeeper-specifications/system-spec/doc.md @@ -0,0 +1,35 @@ + + +# ZooKeeper's System Specification of TLA+ + +## Overview + +ZooKeeper's system specification of TLA+ focuses on the implementation of the Zookeeper Atomic Broadcast(ZAB) consensus protocol (or, [ZAB1.0](https://cwiki.apache.org/confluence/display/ZOOKEEPER/Zab1.0)). + +As is shown by the informal description of [ZAB1.0](https://cwiki.apache.org/confluence/display/ZOOKEEPER/Zab1.0), the implementation of ZAB that used in ZooKeeper production differs a lot from its original design. + +We make this system specification to grasp the core logic of the ZAB's implementation especially. + +The [sysetm specification](zk-3.7/ZkV3_7_0.tla) written in TLA+ is precise without ambiguity, and testable with existed tools like the TLC model checker. (We have done a certain scale of model checking to verify its correctness!) + +The system specification can serve as the super-doc supplementing detailed system documentation for the ZooKeeper developers. It can evolve incrementally without high cost as the system develops over time, continually ensuring correctness for both the design and the implementation. + +We have also made a formal [specification](zk-3.7/FastLeaderElection.tla) for Fast Leader Election in Zab since ZAB 1.0 depends on FLE to complete the election phase. + +If you have any question or find any problem of the specification, please contact us. diff --git a/local-test-zookeeper-delta-01/diff/ref.diff b/local-test-zookeeper-delta-01/diff/ref.diff new file mode 100644 index 0000000000000000000000000000000000000000..e8eaf33cead4f6a0179b931231193edee49308fb --- /dev/null +++ b/local-test-zookeeper-delta-01/diff/ref.diff @@ -0,0 +1,101 @@ +commit 1fac0ad3848bc4e9cb6afd6de004e6c448da20e9 +Author: Isaac Goldthwaite +Date: Wed May 21 14:33:18 2025 -0400 + + [automated] Set delta state + +diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java +index a81a12ba..91952cad 100644 +--- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java ++++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/util/MessageTracker.java +@@ -105,7 +105,9 @@ private static void logMessages( + CircularBuffer messages, + Direction direction) { + String sentOrReceivedText = direction == Direction.SENT ? "sentBuffer to" : "receivedBuffer from"; +- ++ if (serverAddr.contains(":")) { ++ verifyIPv6(serverAddr); ++ } + if (messages.isEmpty()) { + LOG.info("No buffered timestamps for messages {} {}", sentOrReceivedText, serverAddr); + } else { +@@ -116,6 +118,34 @@ private static void logMessages( + } + } + ++ private static void verifyIPv6(String serverAddr) { ++ int maxColons = 8; ++ int cntColons = 0; ++ int i = serverAddr.indexOf(':'); ++ while (i > -1 && i < serverAddr.length() && cntColons < maxColons) { ++ cntColons++; ++ i = serverAddr.indexOf(':', i + 1); ++ } ++ //is there an extra? ++ int extraColons = countExtraColons(i, serverAddr); ++ //count extras ++ if (cntColons > 0 && (cntColons < maxColons || extraColons == 0)) { ++ return; ++ } ++ throw new IllegalArgumentException("bad ipv6: " + serverAddr + " too many colons=" + extraColons); ++ } ++ ++ private static int countExtraColons(int i, String serverAddr) { ++ if (i == -1) { ++ return 1; ++ } ++ int cnt = 1; ++ while (i > 0) { ++ cnt++; ++ i = serverAddr.indexOf(':'); ++ } ++ return cnt; ++ } + /** + * Direction for message track. + */ +diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java +index d400cf99..9e1d6b37 100644 +--- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java ++++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/util/MessageTrackerTest.java +@@ -20,6 +20,9 @@ + + import static org.junit.jupiter.api.Assertions.assertEquals; + import static org.junit.jupiter.api.Assertions.assertNull; ++import static org.junit.jupiter.api.Assertions.assertThrows; ++import static org.junit.jupiter.api.Assertions.assertTrue; ++ + import org.junit.jupiter.api.AfterEach; + import org.junit.jupiter.api.BeforeEach; + import org.junit.jupiter.api.Test; +@@ -127,4 +130,30 @@ public void testDumpToLog() { + assertNull(messageTracker.peekSent()); + assertNull(messageTracker.peekReceived()); + } ++ ++ @Test ++ public void testIPv6VerificationGood() { ++ MessageTracker messageTracker = new MessageTracker(10); ++ //see https://www.ibm.com/docs/en/ts4500-tape-library?topic=functionality-ipv4-ipv6-address-formats ++ for (String serverAddr : new String[] { ++ "2001:db8:3333:4444:5555:6666:7777:8888", ++ "2001:db8:3333:4444:CCCC:DDDD:EEEE:FFFF", ++ "::", "2001:db8::", "2001:db8::1234:5678", ++ "2001:0db8:0001:0000:0000:0ab9:C0A8:0102" ++ }) { ++ messageTracker.dumpToLog(serverAddr); ++ } ++ } ++ ++ @Test ++ public void testIPv6TooManyColons() { ++ final String serverAddr = "2001:db8:1234:0000:0000:0000:0000:0000:0000"; ++ MessageTracker messageTracker = new MessageTracker(10); ++ IllegalArgumentException thrown = assertThrows( ++ IllegalArgumentException.class, ++ () -> messageTracker.dumpToLog(serverAddr), ++ "Expected dumpToLog to throw IllegalArgumentException, but it didn't" ++ ); ++ assertTrue(thrown.getMessage().contains("too many colons=1")); ++ } + } diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/.dockerignore b/local-test-zookeeper-delta-01/fuzz-tooling/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..bd44b7d3383424910d17ba518d801c141f1a466e --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/.dockerignore @@ -0,0 +1,14 @@ +.git +.venv +infra/cifuzz/test_data/* +docs/* + +# Copied from .gitignore. +.vscode/ +*.pyc +build +*~ +.DS_Store +*.swp +.pytest_cache +*__pycache__/* \ No newline at end of file diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/.gitattributes b/local-test-zookeeper-delta-01/fuzz-tooling/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..fc7bee90ffd722b0eb6ebe5ac7f1ea1d0c1cf5e8 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/.gitattributes @@ -0,0 +1,3 @@ +# Check out Linux shell scripts with LF (necessary when using Docker setup on Windows) +*.sh text eol=lf +*.tar.gz filter=lfs diff=lfs merge=lfs -text diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/.pylintrc b/local-test-zookeeper-delta-01/fuzz-tooling/.pylintrc new file mode 100644 index 0000000000000000000000000000000000000000..6126fbc6cb7e562865e0204afbae64a3f854b881 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/.pylintrc @@ -0,0 +1,588 @@ +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code. +extension-pkg-whitelist= + +# Add files or directories to the blocklist. They should be base names, not +# paths. +ignore=CVS,base-clang,base-sanitizer-libs-builder + +# Add files or directories matching the regex patterns to the blocklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the +# number of processors available to use. +jobs=1 + +# Control the amount of potential inferred values when inferring a single +# object. This can help the performance when dealing with large functions or +# complex, nested conditions. +limit-inference-results=100 + +# List of plugins (as comma separated values of python module names) to load, +# usually to register additional checkers. +load-plugins= + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# When enabled, pylint would attempt to guess common misconfiguration and emit +# user-friendly hints instead of false-positive error messages. +suggestion-mode=yes + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED. +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once). You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use "--disable=all --enable=classes +# --disable=W". +disable=print-statement, + parameter-unpacking, + unpacking-in-except, + old-raise-syntax, + backtick, + long-suffix, + old-ne-operator, + old-octal-literal, + import-star-module-level, + non-ascii-bytes-literal, + raw-checker-failed, + bad-inline-option, + locally-disabled, + file-ignored, + suppressed-message, + useless-suppression, + deprecated-pragma, + use-symbolic-message-instead, + apply-builtin, + basestring-builtin, + buffer-builtin, + cmp-builtin, + coerce-builtin, + execfile-builtin, + file-builtin, + long-builtin, + raw_input-builtin, + reduce-builtin, + standarderror-builtin, + unicode-builtin, + xrange-builtin, + coerce-method, + delslice-method, + getslice-method, + setslice-method, + no-absolute-import, + old-division, + dict-iter-method, + dict-view-method, + next-method-called, + metaclass-assignment, + indexing-exception, + raising-string, + reload-builtin, + oct-method, + hex-method, + nonzero-method, + cmp-method, + input-builtin, + round-builtin, + intern-builtin, + unichr-builtin, + map-builtin-not-iterating, + zip-builtin-not-iterating, + range-builtin-not-iterating, + filter-builtin-not-iterating, + using-cmp-argument, + eq-without-hash, + div-method, + idiv-method, + rdiv-method, + exception-message-attribute, + invalid-str-codec, + sys-max-int, + bad-python3-import, + deprecated-string-function, + deprecated-str-translate-call, + deprecated-itertools-function, + deprecated-types-field, + next-method-defined, + dict-items-not-iterating, + dict-keys-not-iterating, + dict-values-not-iterating, + deprecated-operator-function, + deprecated-urllib-function, + xreadlines-attribute, + deprecated-sys-function, + exception-escape, + comprehension-escape, + fixme, + import-error, + logging-fstring-interpolation, + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable=c-extension-no-member + + +[REPORTS] + +# Python expression which should return a score less than or equal to 10. You +# have access to the variables 'error', 'warning', 'refactor', and 'convention' +# which contain the number of messages in each category, as well as 'statement' +# which is the total number of statements analyzed. This score is used by the +# global evaluation report (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details. +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio). You can also give a reporter class, e.g. +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages. +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + +# Complete name of functions that never returns. When checking for +# inconsistent-return-statements if a never returning function is called then +# it will be considered as an explicit return statement and no message will be +# printed. +never-returning-functions=sys.exit + + +[BASIC] + +# Naming style matching correct argument names. +argument-naming-style=snake_case + +# Regular expression matching correct argument names. Overrides argument- +# naming-style. +#argument-rgx= + +# Naming style matching correct attribute names. +attr-naming-style=snake_case + +# Regular expression matching correct attribute names. Overrides attr-naming- +# style. +#attr-rgx= + +# Bad variable names which should always be refused, separated by a comma. +bad-names=foo, + bar, + baz, + toto, + tutu, + tata + +# Naming style matching correct class attribute names. +class-attribute-naming-style=any + +# Regular expression matching correct class attribute names. Overrides class- +# attribute-naming-style. +#class-attribute-rgx= + +# Naming style matching correct class names. +class-naming-style=PascalCase + +# Regular expression matching correct class names. Overrides class-naming- +# style. +#class-rgx= + +# Naming style matching correct constant names. +const-naming-style=UPPER_CASE + +# Regular expression matching correct constant names. Overrides const-naming- +# style. +#const-rgx= + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Naming style matching correct function names. +function-naming-style=snake_case + +# Regular expression matching correct function names. Overrides function- +# naming-style. +#function-rgx= + +# Good variable names which should always be accepted, separated by a comma. +good-names=i, + j, + k, + fp, + ex, + Run, + _ + +# Include a hint for the correct naming format with invalid-name. +include-naming-hint=no + +# Naming style matching correct inline iteration names. +inlinevar-naming-style=any + +# Regular expression matching correct inline iteration names. Overrides +# inlinevar-naming-style. +#inlinevar-rgx= + +# Naming style matching correct method names. +method-naming-style=snake_case + +# Regular expression matching correct method names. Overrides method-naming- +# style. +#method-rgx= + +# Naming style matching correct module names. +module-naming-style=snake_case + +# Regular expression matching correct module names. Overrides module-naming- +# style. +#module-rgx= + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +# These decorators are taken in consideration only for invalid-name. +property-classes=abc.abstractproperty + +# Naming style matching correct variable names. +variable-naming-style=snake_case + +# Regular expression matching correct variable names. Overrides variable- +# naming-style. +#variable-rgx= + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + +# Minimum lines number of a similarity. +min-similarity-lines=4 + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module. +max-module-lines=1000 + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma, + dict-separator + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME, + XXX, + TODO + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# Tells whether to warn about missing members when the owner of the attribute +# is inferred to be None. +ignore-none=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis). It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + +# List of decorators that change the signature of a decorated function. +signature-mutators= + + +[SPELLING] + +# Limits count of emitted suggestions for spelling mistakes. +max-spelling-suggestions=4 + +# Spelling dictionary name. Available dictionaries: none. To make it work, +# install the python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains the private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to the private dictionary (see the +# --spelling-private-dict-file option) instead of raising a message. +spelling-store-unknown-words=no + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid defining new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=no + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_, + _cb + +# A regular expression matching the name of placeholder variables (i.e. expected +# to not be used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore. +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io + + +[LOGGING] + +# Format style used to check logging format string. `old` means using % +# formatting, `new` is for `{}` formatting,and `fstr` is for f-strings. +logging-format-style=old + +# Logging modules to check that the string format arguments are in logging +# function parameter format. +logging-modules=logging + + +[STRING] + +# This flag controls whether the implicit-str-concat-in-sequence should +# generate a warning on implicit string concatenation in sequences defined over +# several lines. +check-str-concat-over-line-jumps=no + + +[IMPORTS] + +# List of modules that can be imported at any level, not just the top level +# one. +allow-any-import-level= + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma. +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled). +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled). +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled). +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Couples of modules and preferred modules, separated by a comma. +preferred-modules= + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__, + __new__, + setUp, + __post_init__ + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict, + _fields, + _replace, + _source, + _make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=cls + + +[DESIGN] + +# Maximum number of arguments for function / method. +max-args=5 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Maximum number of boolean expressions in an if statement (see R0916). +max-bool-expr=5 + +# Maximum number of branch for function / method body. +max-branches=12 + +# Maximum number of locals for function / method body. +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body. +max-returns=6 + +# Maximum number of statements in function / method body. +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "BaseException, Exception". +overgeneral-exceptions=BaseException, + Exception + +# Maximum number of characters on a single line. +max-line-length=80 diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/.style.yapf b/local-test-zookeeper-delta-01/fuzz-tooling/.style.yapf new file mode 100644 index 0000000000000000000000000000000000000000..f1eceb610f1c09b5c2d81c5ac39e87e2af746bc6 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/.style.yapf @@ -0,0 +1,5 @@ +[style] +based_on_style = google +column_limit = 80 +indent_width = 2 +split_before_named_assigns = true diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/CITATION.cff b/local-test-zookeeper-delta-01/fuzz-tooling/CITATION.cff new file mode 100644 index 0000000000000000000000000000000000000000..01916db7d5e098b24a73e8a7296dcf28db56b0b2 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/CITATION.cff @@ -0,0 +1,46 @@ +cff-version: 1.2.0 +title: OSS-Fuzz +message: >- + If you use this software, please cite it using the + metadata from this file. +type: software +authors: + - given-names: Abhishek + family-names: Arya + affiliation: Google LLC + email: aarya@google.com + orcid: 'https://orcid.org/0009-0009-4558-4314' + - given-names: Oliver + family-names: Chang + email: ochang@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0009-0006-3181-4551' + - given-names: Jonathan + family-names: Metzman + email: metzman@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0000-0002-7042-0444' + - given-names: Kostya + family-names: Serebryany + email: kcc@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0009-0009-2379-3641' + - given-names: Dongge + family-names: Liu + email: donggeliu@google.com + affiliation: Google LLC + orcid: 'https://orcid.org/0000-0003-4821-7033' +repository-code: 'https://github.com/google/oss-fuzz' +abstract: >- + OSS-Fuzz is an open-source project by Google that provides + continuous fuzzing for open-source software. It aims to + make common open-source software more secure and stable by + combining modern fuzzing techniques with scalable, + distributed execution. As of August 2023, OSS-Fuzz has + helped identify and fix over 10,000 vulnerabilities and + 36,000 bugs across 1,000 projects. +keywords: + - open-source + - fuzzing +license: Apache-2.0 + diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/CONTRIBUTING.md b/local-test-zookeeper-delta-01/fuzz-tooling/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..425533885614ab036812c924d615bc7949ccbb21 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/CONTRIBUTING.md @@ -0,0 +1,26 @@ +Want to contribute? Great! First, read this page (including the small print at +the end). + +### Before you contribute +Before we can use your code, you must sign the +[Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual) +(CLA), which you can do online. The CLA is necessary mainly because you own the +copyright to your changes, even after your contribution becomes part of our +codebase, so we need your permission to use and distribute your code. We also +need to be sure of various other things: for instance that you'll tell us if you +know that your code infringes on other people's patents. You don't have to sign +the CLA until after you've submitted your code for review and a member has +approved it, but you must do it before we can put your code into our codebase. +Before you start working on a larger contribution, you should get in touch with +us first through the issue tracker with your idea so that we can help out and +possibly guide you. Coordinating up front makes it much easier to avoid +frustration later on. + +### Code reviews +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. + +### The small print +Contributions made by corporations are covered by a different agreement than +the one above, the +[Software Grant and Corporate Contributor License Agreement](https://cla.developers.google.com/about/google-corporate). diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/LICENSE b/local-test-zookeeper-delta-01/fuzz-tooling/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/LICENSE @@ -0,0 +1,201 @@ + 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. diff --git a/local-test-zookeeper-delta-01/fuzz-tooling/README.md b/local-test-zookeeper-delta-01/fuzz-tooling/README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec27ca3e26b6c29906ba8790b1ad00971c6a83e4 --- /dev/null +++ b/local-test-zookeeper-delta-01/fuzz-tooling/README.md @@ -0,0 +1,135 @@ +# OSS-Fuzz-AIxCC: AIxCC AFC Competition fork of OSS-Fuzz (v1.2.0) + +Changes in v1.2.0: + +- `base-builder-jvm` has been updated to use the lastest aixcc-jazzer ref, adjusting the OsCmdInjection sanitizer. + - This adjustment adds some safety measures around OsCmdInjection to reduce risk and reduce potential + unintentional crash-state explosion when dealing with such vulnerabilities. +- `helper.py` commands `build_image`, `build_fuzzers`, and `shell` have added optional flags to control docker image tags. + - Adds the flag `--docker_image_tag TAG` to the commands. This is entirely optional and backwards + compatible, but can allow control over the project-image docker tag, enabling easier parallel processing. +- `helper.py reproduce` has an added optional flag to reproduce with docker running in non-privileged mode. +- `helper.py reproduce` has an added optional flag to timeout when the reproduce subprocess hangs. + - This enables crash detection to handle cases where sanitizers are hit, yet for various reasons the + reproduce subprocess does not resolve and hangs indefinitely. If `timeout` is set, when the reproduce + subprocess does not resolve within `timeout` seconds, reproduce will end the subprocess and return with code 124. + +Changes in v1.1.0: + +- The state of oss-fuzz-aixcc has been synced with upstream changes at 162f2ab818f5992b66486a4d06cb0e3c88c37773. +- `helper.py build_fuzzers` with local source now matches behavior of non-local source, keeping the build state clean between runs. +- `base-image` has been updated to default its locale to C.UTF-8 instead of POSIX. + +This is a competition fork of oss-fuzz which is guaranteed to be +compatible with the AFC challenges. This fork is designed to remain +fully backwards compatible with the public/upstream oss-fuzz, and +thus competition challenges will reflect realistic real-world repositories. + +***Other than base-image changes, the projects files have not been touched +in this repository. The list of projects in the projects directory does +not reflect which projects will be used in any AFC round.*** + +Competitors are recommended to test their CRS against public repositories using this competition fork. +Competitors are recommended to view the [example-crs-architecture] repository's +[example-challenge-evaluation] scripts to see details on how this fuzz tooling is used during competition. + +[example-crs-arhictecture]: https://github.com/aixcc-finals/example-crs-architecture +[example-challenge-evaluation]: https://github.com/aixcc-finals/example-crs-architecture/tree/main/example-challenge-evaluation + +Example basic usage of the helper script is below. **Note: When working with local source, you must pass the local +source repository into the scripts as detailed below.** + +```bash +# Build the project image and pull AFC base images +infra/helper.py build_image --pull + +# Build the fuzzer harnesses for the project, using local source +infra/helper.py build_fuzzers --clean --sanitizer --engine + +# Check all fuzzer harnesses for build +infra/helper.py check_build --sanitizer --engine + +# Reproduce the testcase +# optionally use --propagate_exit_codes +infra/helper.py reproduce +``` + +--- + +# OSS-Fuzz: Continuous Fuzzing for Open Source Software + +[Fuzz testing] is a well-known technique for uncovering programming errors in +software. Many of these detectable errors, like [buffer overflow], can have +serious security implications. Google has found [thousands] of security +vulnerabilities and stability bugs by deploying [guided in-process fuzzing of +Chrome components], and we now want to share that service with the open source +community. + +[Fuzz testing]: https://en.wikipedia.org/wiki/Fuzz_testing +[buffer overflow]: https://en.wikipedia.org/wiki/Buffer_overflow +[thousands]: https://issues.chromium.org/issues?q=label:Stability-LibFuzzer%20-status:Duplicate,WontFix +[guided in-process fuzzing of Chrome components]: https://security.googleblog.com/2016/08/guided-in-process-fuzzing-of-chrome.html + +In cooperation with the [Core Infrastructure Initiative] and the [OpenSSF], +OSS-Fuzz aims to make common open source software more secure and stable by +combining modern fuzzing techniques with scalable, distributed execution. +Projects that do not qualify for OSS-Fuzz (e.g. closed source) can run their own +instances of [ClusterFuzz] or [ClusterFuzzLite]. + +[Core Infrastructure Initiative]: https://www.coreinfrastructure.org/ +[OpenSSF]: https://www.openssf.org/ + +We support the [libFuzzer], [AFL++], and [Honggfuzz] fuzzing engines in +combination with [Sanitizers], as well as [ClusterFuzz], a distributed fuzzer +execution environment and reporting tool. + +[libFuzzer]: https://llvm.org/docs/LibFuzzer.html +[AFL++]: https://github.com/AFLplusplus/AFLplusplus +[Honggfuzz]: https://github.com/google/honggfuzz +[Sanitizers]: https://github.com/google/sanitizers +[ClusterFuzz]: https://github.com/google/clusterfuzz +[ClusterFuzzLite]: https://google.github.io/clusterfuzzlite/ + +Currently, OSS-Fuzz supports C/C++, Rust, Go, Python, Java/JVM, and JavaScript code. Other languages +supported by [LLVM] may work too. OSS-Fuzz supports fuzzing x86_64 and i386 +builds. + +[LLVM]: https://llvm.org + +## Overview +![OSS-Fuzz process diagram](docs/images/process.png) + +## Documentation +Read our [detailed documentation] to learn how to use OSS-Fuzz. + +[detailed documentation]: https://google.github.io/oss-fuzz + +## Trophies +As of August 2023, OSS-Fuzz has helped identify and fix over [10,000] vulnerabilities and [36,000] bugs across [1,000] projects. + +[10,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug-Security%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[36,000]: https://bugs.chromium.org/p/oss-fuzz/issues/list?q=Type%3DBug%20label%3Aclusterfuzz%20-status%3ADuplicate%2CWontFix&can=1 +[1,000]: https://github.com/google/oss-fuzz/tree/master/projects + +## Blog posts +* 2023-08-16 - [AI-Powered Fuzzing: Breaking the Bug Hunting Barrier] +* 2023-02-01 - [Taking the next step: OSS-Fuzz in 2023] +* 2022-09-08 - [Fuzzing beyond memory corruption: Finding broader classes of vulnerabilities automatically] +* 2021-12-16 - [Improving OSS-Fuzz and Jazzer to catch Log4Shell] +* 2021-03-10 - [Fuzzing Java in OSS-Fuzz] +* 2020-12-07 - [Improving open source security during the Google summer internship program] +* 2020-10-09 - [Fuzzing internships for Open Source Software] +* 2018-11-06 - [A New Chapter for OSS-Fuzz] +* 2017-05-08 - [OSS-Fuzz: Five months later, and rewarding projects] +* 2016-12-01 - [Announcing OSS-Fuzz: Continuous fuzzing for open source software] + +[AI-Powered Fuzzing: Breaking the Bug Hunting Barrier]: https://security.googleblog.com/2023/08/ai-powered-fuzzing-breaking-bug-hunting.html +[Announcing OSS-Fuzz: Continuous fuzzing for open source software]: https://opensource.googleblog.com/2016/12/announcing-oss-fuzz-continuous-fuzzing.html +[OSS-Fuzz: Five months later, and rewarding projects]: https://opensource.googleblog.com/2017/05/oss-fuzz-five-months-later-and.html +[A New Chapter for OSS-Fuzz]: https://security.googleblog.com/2018/11/a-new-chapter-for-oss-fuzz.html +[Fuzzing internships for Open Source Software]: https://security.googleblog.com/2020/10/fuzzing-internships-for-open-source.html +[Improving open source security during the Google summer internship program]: https://security.googleblog.com/2020/12/improving-open-source-security-during.html +[Fuzzing Java in OSS-Fuzz]: https://security.googleblog.com/2021/03/fuzzing-java-in-oss-fuzz.html +[Improving OSS-Fuzz and Jazzer to catch Log4Shell]: https://security.googleblog.com/2021/12/improving-oss-fuzz-and-jazzer-to-catch.html +[Fuzzing beyond memory corruption: Finding broader classes of vulnerabilities automatically]: https://security.googleblog.com/2022/09/fuzzing-beyond-memory-corruption.html +[Taking the next step: OSS-Fuzz in 2023]: https://security.googleblog.com/2023/02/taking-next-step-oss-fuzz-in-2023.html